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

2024-06-08 02:34:42 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我是新进入regex和我开始与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']

请告诉我哪里出错了。


Tags: importreyouhellohaveshop单词what
1条回答
网友
1楼 · 发布于 2024-06-08 02:34:42

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

相关问题 更多 >

    热门问题