【问题标题】:Python regex for finding all words in a string [duplicate]用于查找字符串中所有单词的 Python 正则表达式 [重复]
【发布时间】:2016-09-29 08:23:20
【问题描述】:
您好,我是 regex 的新手,我从 python 开始。
我坚持从英语句子中提取所有单词。
到目前为止,我有:
import re
shop="hello seattle what have you got"
regex = r'(\w*) '
list1=re.findall(regex,shop)
print list1
这给出了输出:
['你好','西雅图','什么','有','你']
如果我将正则表达式替换为
regex = r'(\w*)\W*'
然后输出:
['你好','西雅图','什么','有','你','得到','']
而我想要这个输出
['你好','西雅图','什么','有','你','得到']
请指出我哪里出错了。
【问题讨论】:
标签:
python
regex
words
sentence
【解决方案1】:
使用字边界\b
import re
shop="hello seattle what have you got"
regex = r'\b\w+\b'
list1=re.findall(regex,shop)
print list1
OP : ['hello', 'seattle', 'what', 'have', 'you', 'got']
或者只是\w+就足够了
import re
shop="hello seattle what have you got"
regex = r'\w+'
list1=re.findall(regex,shop)
print list1
OP : ['hello', 'seattle', 'what', 'have', 'you', 'got']