python - 正则表达式从Python中的单词列表中提取给定单词之前的一个单词
问题描述
我想为这个问题提取一个词——谁吃了苹果。就像字符串是“Ujjwal ate the apple”一样。所以它应该使用正则表达式提取单词 'Ujjwal',在单词 ate 之前的一个单词。任何人都可以帮助我使用正则表达式吗?在蟒蛇。
实际上,我有一个列表,上面有“吃”、“吃”、“吃”之类的词,就像“Ujjwal 吃过苹果”一样。这里也应该提取 Ujjwal。如何检查列表中的单词而不仅仅是“吃”本身?
解决方案
如果您有一个单词列表并且想要获得一个正则表达式来匹配 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)'
推荐阅读
- sql - 如何从 Firebird DB 中读取所有“last_changed”记录?
- python - 如何在单独的列表中收集每个子目录中的文件名
- .net - 让不同的组安装不同的 ClickOnce 版本
- python - ODOO12:不创建数据库列?
- ios - Swift 无法读取 csv
- css - CSS 文件未在 localhost 上完全加载
- python - 如何以最佳方式在 PySpark 中以两个条件连接两个表
- c# - c# excel将多色文本写入同一个单元格
- mysql - 在 MySQL 中优化和分区具有 3 亿条记录的大表的最佳方法
- java - JAVA:我需要按降序对数组中的系列进行排序