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

时间:2015-04-23 10:28:34

标签: python arrays python-2.7 search arraylist

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

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

4 个答案:

答案 0 :(得分:1)

searchfile = open('keywords.txt', 'r')
infile = open('text.txt', 'r')

for keywords in searchfile:
    for lines in infile:
        if keywords in lines:
           print lines

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

你可以试试这个:

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)

答案 3 :(得分:0)

将关键字设为set,检查该行中的任何字词是否在集合中:

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)

如果您不拆分"green" in 'my shirt is greenish' -> True。您还必须考虑标点符号和案例。

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

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)