[英]In Python, searching a text file for multiple words and printing the corresponding lines
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)
This code doesn't work because "item" isn't defined. 该代码无效,因为未定义“项目”。 Anyway I could get this done?
无论如何,我可以做到这一点? I'm a newbie with python.
我是python的新手。
Try this: 尝试这个:
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)
# with Regular Expression
import re
fruit_list = open('test.txt')
search_words = ['apple', 'banana', 'orange', 'lemon']
patten = re.compile("(.*(apple|banana|orange|lemon)(.*))")
for i in [re.search(patten,line).groups() for line in fruit_list if re.search(patten,line) != None]: print(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.