我编写了这段代码,用于检查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 :(得分:0)
这是一种方式
if len(set(line.split()).intersection(keywords)) > 2:
首先将该行拆分为line.split()
的单词
。然后使用sets intersection函数查找2组