如何使用正则表达式在单词边界处分割? [英] How can I split at word boundaries with regexes?
本文介绍了如何使用正则表达式在单词边界处分割?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试这样做:
import re
sentence = "How are you?"
print(re.split(r'\b', sentence))
结果是
[u'How are you?']
我想要类似[u'How', u'are', u'you', u'?']
的东西.如何实现?
I want something like [u'How', u'are', u'you', u'?']
. How can this be achieved?
推荐答案
不幸的是,Python无法用空字符串分割.
Unfortunately, Python cannot split by empty strings.
要解决此问题,您需要使用findall
而不是split
.
To get around this, you would need to use findall
instead of split
.
实际上\b
仅表示单词边界.
Actually \b
just means word boundary.
等效于(?<=\w)(?=\W)|(?<=\W)(?=\w)
.
这意味着,以下代码将起作用:
That means, the following code would work:
import re
sentence = "How are you?"
print(re.findall(r'\w+|\W+', sentence))
这篇关于如何使用正则表达式在单词边界处分割?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文