2015-04-23 272 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) 
相關問題