Python-如何将re.finditer与多个模式一起使用
我想在一个字符串中搜索3个单词,并将它们放在一个列表中 比如:Python-如何将re.finditer与多个模式一起使用,python,regex,python-3.x,findall,Python,Regex,Python 3.x,Findall,我想在一个字符串中搜索3个单词,并将它们放在一个列表中 比如: 句子=“汤姆有一次得到一辆自行车,他把它忘在外面淋雨,所以它生锈了” pattern=['had','which','got'] 答案应该是这样的: ['got','which','had','got'] 我还没有找到这样使用re.finditer的方法。很遗憾,我需要使用finditer 相反,findall您可以从搜索的单词列表中构建模式,然后根据finditer返回的匹配项构建具有列表理解力的输出列表: import re
句子=“汤姆有一次得到一辆自行车,他把它忘在外面淋雨,所以它生锈了”
pattern=['had','which','got']
答案应该是这样的:
['got','which','had','got']
我还没有找到这样使用re.finditer
的方法。很遗憾,我需要使用finditer
相反,
findall
您可以从搜索的单词列表中构建模式,然后根据finditer
返回的匹配项构建具有列表理解力的输出列表:
import re
sentence = "Tom once got a bike which he had left outside in the rain so it got rusty"
pattern = ['had', 'which', 'got' ]
regex = re.compile(r'\b(' + '|'.join(pattern) + r')\b')
# the regex will be r'\b(had|which|got)\b'
out = [m.group() for m in regex.finditer(sentence)]
print(out)
# ['got', 'which', 'had', 'got']
您可以根据搜索词列表构建模式,然后根据
finditer
返回的匹配项以列表理解的方式构建输出列表:
import re
sentence = "Tom once got a bike which he had left outside in the rain so it got rusty"
pattern = ['had', 'which', 'got' ]
regex = re.compile(r'\b(' + '|'.join(pattern) + r')\b')
# the regex will be r'\b(had|which|got)\b'
out = [m.group() for m in regex.finditer(sentence)]
print(out)
# ['got', 'which', 'had', 'got']
其思想是将模式列表的条目组合起来,形成一个带有或s的正则表达式。 然后,您可以使用以下代码片段:
import re
sentence = 'Tom once got a bike which he had left outside in the rain so it got rusty. ' \
'Luckily, Margot and Chad saved money for him to buy a new one.'
pattern = ['had', 'which', 'got']
regex = re.compile(r'\b({})\b'.format('|'.join(pattern)))
# regex = re.compile(r'\b(had|which|got)\b')
results = [match.group(1) for match in regex.finditer(sentence)]
print(results)
结果是
['got','which','had','got']
这个想法是将模式列表的条目组合成一个带有或的正则表达式。
然后,您可以使用以下代码片段:
import re
sentence = 'Tom once got a bike which he had left outside in the rain so it got rusty. ' \
'Luckily, Margot and Chad saved money for him to buy a new one.'
pattern = ['had', 'which', 'got']
regex = re.compile(r'\b({})\b'.format('|'.join(pattern)))
# regex = re.compile(r'\b(had|which|got)\b')
results = [match.group(1) for match in regex.finditer(sentence)]
print(results)
结果是
['got','which','had','got']
那么为什么要标记findall?您尝试了什么?你能展示你的尝试吗?那你为什么给芬德尔贴标签?你尝试了什么?你能展示一下你的尝试吗?你的正则表达式也会匹配“Margot”中的“got”和“Chad”中的“had”谢谢,我加入了你的提示。你的正则表达式也会匹配“Margot”中的“got”和“Chad”中的“had”谢谢,我加入了你的提示。