如何删除python中仅包含数字的单词? [英] How to remove words containing only numbers in python?
问题描述
我在 Python 中有一些由数字和字母组成的文本.像这样:
s = "12 word word2"
从字符串 s 中,我想删除所有包含仅数字
的单词所以我希望结果是
s = "word word2"
这是我拥有的正则表达式,但它适用于字母表,即它用空格替换每个字母表.
re.sub('[\ 0-9\ ]+', ' ', line)
有人可以帮忙告诉我出了什么问题吗?另外,有没有比正则表达式更省时的方法?
谢谢!
你可以使用这个正则表达式:
<预><代码>>>>s = "12 字 word2">>>打印 re.sub(r'\b[0-9]+\b\s*', '', s)字字2\b
用于单词边界,\s*
将删除数字单词后的 0 个或多个空格.
I have some text in Python which is composed of numbers and alphabets. Something like this:
s = "12 word word2"
From the string s, I want to remove all the words containing only numbers
So I want the result to be
s = "word word2"
This is a regex I have but it works on alphabets i.e. it replaces each alphabet by a space.
re.sub('[\ 0-9\ ]+', ' ', line)
Can someone help in telling me what is wrong? Also, is there a more time-efficient way to do this than regex?
Thanks!
You can use this regex:
>>> s = "12 word word2"
>>> print re.sub(r'\b[0-9]+\b\s*', '', s)
word word2
\b
is used for word boundary and \s*
will remove 0 or more spaces after your number word.
这篇关于如何删除python中仅包含数字的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!