Python正则表达式,用于查找字符串中的所有单词 [英] Python regex for finding all words in a string
本文介绍了Python正则表达式,用于查找字符串中的所有单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,我是regex的新手,我从python开始. 我一直坚持从英语句子中提取所有单词. 到目前为止,我有:
Hello I am new into regex and I'm starting out with python. I'm stuck at extracting all words from an English sentence. So far I have:
import re
shop="hello seattle what have you got"
regex = r'(\w*) '
list1=re.findall(regex,shop)
print list1
这给出了输出:
['hello','seattle','what','have','you']
['hello', 'seattle', 'what', 'have', 'you']
如果我将regex替换为
If I replace regex by
regex = r'(\w*)\W*'
然后输出:
['hello','seattle','what','have','you','got','']
['hello', 'seattle', 'what', 'have', 'you', 'got', '']
我想要这个输出
['hello','seattle','what','have','you','got']
['hello', 'seattle', 'what', 'have', 'you', 'got']
请指出我要去哪里了.
推荐答案
使用单词边界\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']
这篇关于Python正则表达式,用于查找字符串中的所有单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文