在python中使用re.sub函数删除字符串中的特殊字符、撇号和不需要的空格
我想要结果:在python中使用re.sub函数删除字符串中的特殊字符、撇号和不需要的空格,python,python-2.7,Python,Python 2.7,我想要结果: import re def removePunctuation(text): return re.sub(r'[ \W,_,]+', ' ', text.lower()).lstrip() print removePunctuation('Hi, 'you!') print removePunctuation(' No's under_score!') 你可以试试这个 hi you nos under score 或 似乎要用空格替换所有下划线,用空字符串替换所有其
import re
def removePunctuation(text):
return re.sub(r'[ \W,_,]+', ' ', text.lower()).lstrip()
print removePunctuation('Hi, 'you!')
print removePunctuation(' No's under_score!')
你可以试试这个
hi you
nos under score
或
似乎要用空格替换所有下划线,用空字符串替换所有其他特殊字符
def removePunctuation(text):
return re.sub(r'^\s+|\s+$|[^A-Za-z\d\s]', '', text.lower())
Regex是一个非常好的字符串操作工具,但在python中,它有时可能是一个过度使用的工具,这个特殊的例子就是其中之一。 Python考虑了一些精心构建的字符串库,它们可以在没有正则表达式的情况下创造奇迹,对于本例来说,str.translate和unicode.translate是理想的选择 对于Python2.X 对于Unicode和Python 3.X
你想转向太空吗?请澄清你的要求。
>>> re.sub(r'^\s+|\s+$|[^A-Za-z\d\s]', '', " No's under_score!".lower().replace('_', ' '))
'nos under score'
>>> re.sub(r'^\s+|\s+$|[^A-Za-z\d\s]', '', " Hi, 'you!'".lower().replace('_', ' '))
'hi you'
def removePunctuation(text):
from string import punctuation
return ' '.join(text.translate(None, punctuation))
def removePunctuationU(text):
from string import punctuation
return u' '.join(text.translate({ord(c): None for c in punctuation}).split())