2013-01-08 208 views

回答

1

這會給你一個開始:

words = ['a', 'and', 'foo'] 
infile = open('myfile.txt', 'r') 
match_sentences = [] 

for line in infile.readlines(): 
    # check for words in this line 
    # if match, append to match_sentences list 
4
sentences = [line for line in f if any(word in line for word in word_list)] 

這裏f將是你的文件對象,例如,你可以用open('file.txt')如果file.txt是你的文件的名稱替換它,它位於與腳本相同的目錄。

2

使用set.intersection

with open('file') as f: 
    [line for line in f if set(line.lower().split()).itersection(word_set)] 

filter

filter(lambda x:word_set.intersection(set(x.lower().split())),f) 
相關問題