首页 > 解决方案 > 正则表达式从Python中的单词列表中提取给定单词之前的一个单词

问题描述

我想为这个问题提取一个词——谁吃了苹果。就像字符串是“Ujjwal ate the apple”一样。所以它应该使用正则表达式提取单词 'Ujjwal',在单词 ate 之前的一个单词。任何人都可以帮助我使用正则表达式吗?在蟒蛇。

实际上,我有一个列表,上面有“吃”、“吃”、“吃”之类的词,就像“Ujjwal 吃过苹果”一样。这里也应该提取 Ujjwal。如何检查列表中的单词而不仅仅是“吃”本身?

标签: pythonpython-3.xregex

解决方案


如果您有一个单词列表并且想要获得一个正则表达式来匹配 Python 中的单词列表,您可以定义一个带有 (or) 的子模式|并连接单词列表中的单词的模式。例如:

import re

word_list = ['ate', 'eat', 'eaten']

pattern = rf'(\w+)\s*(?:\b(?:{"|".join(word_list)})\b)'

result1 = re.findall(pattern, 'Ujjwal ate the apple.')

print(result1)
# output:
['Ujjwal']

result2 = re.findall(pattern, 'Ujjwal eaten the apple.')

print(result2)
# output:
['Ujjwal']

在这里,我们使用 r-string 和 f-string 来保存模式。

{"|".join(word_list)}在 f-string 中将解析为ate|eat|eaten,有效地将正则表达式设为r'(\w+)\s*(?:\b(?:ate|eat|eaten)\b)'


推荐阅读