2014-06-24 79 views
-5

我已经编写了这些代码,用于检查infile中哪些行与关键字文件中的所有关键字匹配。现在,我希望它找到所有只包含两个或更多关键字的行。查找包含列表中两个或更多单词的行

infile = open('/Path/#input.txt', 'r') 
outfile = open('/Path/#output.txt', 'w') 

# Read a textfile containing keywords to find 
# (and strip the newline character '\n') 
keywords = [line.strip() for line in open('Path/#keywords.txt')] 

# See which lines in the infile match ALL of the keywords 
# and write those lines to the outfile 
for line in infile: 
    if all(k in line for k in keywords): 
     outfile.write(line) 

回答

0

这里是单程

if len(set(line.split()).intersection(keywords)) > 2: 

此分割线成单词与line.split()第一 。然后使用sets intersection函数找到2组的共同元素

+1

我认为你是split() –

+1

后缺少')'是的,谢谢,修复 –

+0

对不起,如果我误解了这一点,但是找到2套共同元素与在infile中查找包含关键字文件中至少两个单词的行相同的内容? – textnet

相关问题