有人可以用正则表达式帮我一点吗?我目前有这个:re.split(" +", line.rstrip())
,用空格分隔。
我怎么能扩展它以涵盖标点符号呢?
官方Python文档就是这方面的一个很好的例子。它将拆分所有非字母数字字符(空格和标点符号)。字面上\ W是所有非Word字符的字符类。注意:下划线“_”被视为“单词”字符,不会成为此处拆分的一部分。
re.split('\W+', 'Words, words, words.')
有关更多示例,请参阅https://docs.python.org/3/library/re.html,搜索“re.split”的页面
使用string.punctuation
和字符类:
>>> from string import punctuation
>>> r = re.compile(r'[\s{}]+'.format(re.escape(punctuation)))
>>> r.split('dss!dfs^ #$% jjj^')
['dss', 'dfs', 'jjj', '']
import re
st='one two,three; four-five, six'
print re.split(r'\s+|[,;.-]\s*', st)
# ['one', 'two', 'three', 'four', 'five', 'six']