【发布时间】:2013-11-22 13:17:26
【问题描述】:
任何人都可以帮助我使用正则表达式吗?我目前有这个:re.split(" +", line.rstrip()),用空格隔开。
我怎样才能扩展它以涵盖标点符号呢?
【问题讨论】:
标签: python regex string split punctuation
任何人都可以帮助我使用正则表达式吗?我目前有这个:re.split(" +", line.rstrip()),用空格隔开。
我怎样才能扩展它以涵盖标点符号呢?
【问题讨论】:
标签: python regex string split punctuation
官方 Python 文档有一个很好的例子。它将拆分所有非字母数字字符(空格和标点符号)。从字面上看,\W 是所有非单词字符的字符类。注意:下划线“_”被认为是一个“单词”字符,不会成为此处拆分的一部分。
re.split('\W+', 'Words, words, words.')
更多示例请参见https://docs.python.org/3/library/re.html,搜索页面“re.split”
【讨论】:
' 和" 和* 上拆分?这个答案就是这样做的。如My name's steve 将拆分为My name 和s steve。
import regex; L = regex.split(ur"\W+", u"किशोरी")
使用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']
【讨论】:
[][,;.-]
当您考虑使用正则表达式与任何标点符号进行拆分时,您应该记住\W 模式不匹配下划线(这也是一个标点符号字符)。
因此,您可以使用
import re
tokens = re.split(r'[\W_]+', text)
[\W_] 匹配任何 Unicode 非字母数字字符。
由于re.split可能会在匹配出现在字符串的开头或结尾时返回空项,因此最好使用正逻辑并使用
import re
tokens = re.findall(r'[^\W_]+', text)
[^\W_] 匹配任何 Unicode 字母数字字符。
import re
text = "!Hello, world!"
print( re.split(r'[\W_]+', text) )
# => ['', 'Hello', 'world', '']
print( re.findall(r'[^\W_]+', text) )
# => ['Hello', 'world']
【讨论】: