gpt4 book ai didi

python - 从文件中提取特定单词

转载 作者:行者123 更新时间:2023-12-01 08:07:14 25 4
gpt4 key购买 nike

我正在分析一些文本文件,每次在文件中找到该单词时,我想提取该单词。

假设我的文件中有“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

如何只打印列表中的单词而不是所有行?

谢谢!

最佳答案

列表.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']]

:

line 1 had sports and football

line 2 had no matching elements from content list

line 3 had football

关于python - 从文件中提取特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55478056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com