python - 从文件中提取特定单词
问题描述
我正在分析一些文本文件,并且每次在文件中找到该单词时,我都想提取该特定单词。
想象一下,我在文件中有“Sports”,然后我想根据列表提取单词“SPORTS”。
我有以下代码:
content = ['Sports', 'Nature', 'Football']
path = filename
with open(path) as auto:
for line in auto:
if any(x.lower() in line.lower() for x in content):
print(line)
我的文本文件包含以下内容:
Sports TV is the home of football videos.
Complex game to follow.
home of football
使用我的代码,我打印所有带有“体育”和“足球”的行:
Sports TV is the home of football videos.
home of football
但我想看到以下结果:
Sports
football
如何仅打印 List 上的单词而不是所有行?
谢谢!
解决方案
列表.txt:
Sports TV is the home of football videos.
Complex game to follow.
home of football
因此:
content = ['Sports', 'Nature', 'Football']
path = 'list.txt'
with open(path) as auto:
print([[x.lower() for x in content if x.lower() in line.lower()] for line in auto])
输出:
[['sports', 'football'], [], ['football']]
自:
第 1 行有
sports
和football
第 2 行没有来自内容列表的匹配元素
3号线有
football
推荐阅读
- git - 从 HEAD 签出文件的原因 ^ 将文件放在暂存区
- postgresql - 运行 psql 命令时出现 psql 的符号查找错误
- java - 如何使用来自 html 表单的 POST 的 Spring Security?
- c# - 使用 Newtonsoft.Json 将名称反序列化为值
- json - Swift 5:如何从 JSONDecoder().decode 获取数据?
- python - 如何在 PyGame 中添加摩擦力
- linux - Dockerized nginx 在 ssl 模式下失败
- angular - 角度动态路径数
- sql - 如何从 Postgresql 中的计算列中获取平均值?
- sql - Oracle SQL:返回每个 ID 和产品名称的最早和最晚日期记录