Python 如何使用关键字从txt文件中搜索和检索整行

Python 如何使用关键字从txt文件中搜索和检索整行,python,arrays,python-2.7,search,arraylist,Python,Arrays,Python 2.7,Search,Arraylist,搜索工作,除了我有一个keywords.txt文件包含简单的单词,如“green,blue等”(都在自己的行上),然后我有一个文本,如“我的衬衫是绿色的”,当我使用此代码时,它不会找到任何东西,但如果我将txt文件中的句子改为一个单词,它会找到它。我需要它在文档中搜索关键字,然后显示它所在的整行内容 试试这个 searchfile =open('test.txt','r') for line in searchfile: if line in array: print l

搜索工作,除了我有一个keywords.txt文件包含简单的单词,如“green,blue等”(都在自己的行上),然后我有一个文本,如“我的衬衫是绿色的”,当我使用此代码时,它不会找到任何东西,但如果我将txt文件中的句子改为一个单词,它会找到它。我需要它在文档中搜索关键字,然后显示它所在的整行内容

试试这个

searchfile =open('test.txt','r')
    for line in searchfile:
        if line in array: print line
    searchfile.close() 
searchfile = open('keywords.txt', 'r')
infile = open('text.txt', 'r')

for keywords in searchfile:
    for lines in infile:
        if keywords in lines:
           print lines
您可以尝试以下方法:

searchfile = None
with open('test.txt','r') as f:
    searchfile = f.readlines()
    f.close()

for line in searchfile:
    for word in array:
        if word in line:
            print line

将关键字设置为一个
集合
,检查行中是否有单词在集合中:

searchFile = open('keywords.txt','r')
file = open('text.txt','r') 
file1 = file.readlines()  
file.close()
for key in searchFile:
    for line in file1:
        if key in Line:
             print (line)
如果您不在“我的衬衫是绿色的”中拆分
“绿色”->则为True
。你还必须考虑标点和大小写

如果要忽略大小写并删除标点符号,可以使用
str.lower
str.strip

with open('search.txt','r') as f1, open("keywords.txt") as f2:
    st = set(map(str.rstrip, f2))
    for line in f1:
        if any(word in st for word in  line.split()):
            print(line)
from string import punctuation
with open('search.txt','r') as f1, open("keywords.txt") as f2:
    st = set(map(str.rstrip, f2))
    for line in f1:
        if any(word.lower().strip(punctuation) in st for word in line.split()):
            print(line)