从文件中提取特定单词

我正在分析一些文本文件,每次在文件中找到该词时,我都想提取一个特定的词。


想象一下,我在文件中有“体育”,然后我想根据列表提取单词“体育”。


我有以下代码:


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 上的单词而不是所有行?


不负相思意
浏览 203回答 2
2回答

翻过高山走不出你

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

函数式编程

您目前正在打印整行尝试:content = ['Sports', 'Nature', 'Football']path = filenamewith open(path) as auto:    for line in auto:        for x in content:            if x.lower() in line.lower():                print(x)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python