在Python中,在文本文件中搜索多个单词并打印相应的行 [英] In Python, searching a text file for multiple words and printing the corresponding lines

查看:67
本文介绍了在Python中,在文本文件中搜索多个单词并打印相应的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要搜索的句子列表.我想打印包含搜索词的行.这段代码有效:

I have a list of sentences I would like to search. I want to print the lines that contain my search words. This code works:

fruit_list = open('fruitlist.txt')
for line in fruit_list:
    if 'apple' in line or 'banana' in line or 'orange' in line:
        print (line)

但是这可能非常乏味.特别是如果我希望我的搜索词列表更长.我想列出一个搜索词,并使用它来搜索文档并打印该行.

But this can be pretty tedious; especially if I want my list of search words to be longer. I would like to make a list of search words and use that to search the document and print the line.

search_words=['apple','banana','orange','lemon']
for line in fruit_list:
    if item in search_words in line:
        print (line)

此代码无效,因为未定义项目".无论如何,我能做到这一点吗?我是python的新手.

This code doesn't work because "item" isn't defined. Anyway I could get this done? I'm a newbie with python.

推荐答案

尝试一下:

fruit_list = open('fruitlist.txt')

search_words = ['apple', 'banana', 'orange', 'lemon']

for line in fruit_list:
    if any(word in line for word in search_words):
        print(line)

这篇关于在Python中,在文本文件中搜索多个单词并打印相应的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆