我想迭代一些行(包含文本)并仅返回包含关键字列表中两个或多个单词的那些行。
我一直在努力将wordlist和keywordlist变成集合以使用intersect函数,例如:
if len(set(line).intersection(set(keywords))) >1:
print line
还尝试了各种类型的嵌套循环,如
if word in line
但还没有成功。
答案 0 :(得分:3)
您需要使用str.split
并在将空格转换为集合之前拆分空白行:
if len(set(line.split()).intersection(set(keywords))) > 1:
参见下面的演示:
>>> keywords = ['if', 'def', 'class']
>>> line = 'if def word'
>>> len(set(line).intersection(set(keywords))) > 1
False
>>> len(set(line.split()).intersection(set(keywords))) > 1
True
>>>
如果没有此更改,您将获得一组字符而不是一组字词:
>>> line = 'if def word'
>>> set(line)
{' ', 'f', 'd', 'e', 'i', 'o', 'r', 'w'}
>>> set(line.split())
{'word', 'if', 'def'}
>>>