0

我有一段简单的代码,它告诉我给定列表中的单词是否出现在文章中:

 if not any(word in article.text for word in keywords):
        print("Skipping article as there is no matching keyword\n")

我需要的是,如果“关键字”列表中至少有 3 个单词出现在文章中 - 如果没有,那么它应该跳过文章。

是否有捷径可寻?我似乎找不到任何东西。

4

3 回答 3

3

您可以使用此模式计算满足条件的项目数:

sum(1 for x in xs if c(x))

在这里你会做:

if sum(1 for word in keywords if word in article.text) >= 3:
    # 
于 2016-01-05T06:06:29.880 回答
2

如果关键字集足够大并且要搜索的字符串足够长以至于通常值得短路,则其他方法的变体将在找到三个匹配项时any停止(很像找到一个匹配项时停止):

from itertools import islice

if sum(islice((1 for word in keywords if word in article.text), 3)) == 3:

一旦你得到三个点击,它会立即停止迭代关键字并且测试通过。

于 2016-01-05T06:33:24.507 回答
0

我的文字和列表很长

如果文本很大并且有很多关键字,那么您可以使用Aho-Corasick 算法(例如grep -Ff keywords.txt text.txt),例如,如果您想找到不重叠的事件,您可以使用noaho(未测试):

#!/usr/bin/env python
from itertools import islice
from noaho import NoAho  # $ pip install noaho

trie = NoAho()
for word in keywords:
    trie.add(word)
found_words = trie.findall_long(article.text)
if len(list(islice(found_words, 3))) == 3:
    print('at least 3 words in the "keywords" list appear in the article')
于 2016-01-06T02:40:15.870 回答