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