2015-04-23 276 views
1
searchfile =open('test.txt','r') 
    for line in searchfile: 
     if line in array: print line 
    searchfile.close() 

搜索工作,除了我有一个包含像“绿,蓝等”简单的单词keywords.txt文件(全部在自己的行)然后我有当我使用这段代码时,如果我将txt文件中的句子更改为只有一个单词,它就会发现它,但它不会找到任何内容。我需要它来搜索文档的关键字,然后显示整条生产线,这是在如何搜索和使用检索一个txt文件全行关键字

回答

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 
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 
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) 
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) 
相关问题