Python正则表达式:查找字符串中的所有单词

9

你好,我刚接触正则表达式,并开始使用Python。我在从英文句子中提取所有单词的过程中遇到了困难。目前我所写的代码如下:

import re

shop="hello seattle what have you got"
regex = r'(\w*) '
list1=re.findall(regex,shop)
print list1

这将产生以下输出:

['hello'、'seattle'、'what'、'have'、'you']

如果我用以下正则表达式替换:

regex = r'(\w*)\W*'

然后输出:

['hello', 'seattle', 'what', 'have', 'you', 'got', '']

而我想要的输出是:

['hello', 'seattle', 'what', 'have', 'you', 'got']

请指出我哪里做错了。

1个回答

21

使用单词边界 \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']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接