正则表达式标点分割[Python]

问题描述 投票:19回答:3

有人可以用正则表达式帮我一点吗?我目前有这个:re.split(" +", line.rstrip()),用空格分隔。

我怎么能扩展它以涵盖标点符号呢?

python regex string split punctuation
3个回答
27
投票

官方Python文档就是这方面的一个很好的例子。它将拆分所有非字母数字字符(空格和标点符号)。字面上\ W是所有非Word字符的字符类。注意:下划线“_”被视为“单词”字符,不会成为此处拆分的一部分。

re.split('\W+', 'Words, words, words.')

有关更多示例,请参阅https://docs.python.org/3/library/re.html,搜索“re.split”的页面


15
投票

使用string.punctuation和字符类:

>>> from string import punctuation
>>> r = re.compile(r'[\s{}]+'.format(re.escape(punctuation)))
>>> r.split('dss!dfs^  #$% jjj^')
['dss', 'dfs', 'jjj', '']

3
投票
import re
st='one two,three; four-five,    six'

print re.split(r'\s+|[,;.-]\s*', st)
# ['one', 'two', 'three', 'four', 'five', 'six']
© www.soinside.com 2019 - 2024. All rights reserved.