我要完成的任务是编写一个函数,该函数将识别至少在y条目中搜索字符串列表中至少在y条目中发生的所有模式。
例如:
list = ["Hello my name is foobar","Hello my favorite food is pizza","Hello my favorite food will never be broccoli","No my name is not barfoo", "Yes my name is foobar"]
然后
function(list, n=3, y=3)
["my name is"]
function(list, n=3, y=2)
["my name is", "my favorite food"]
我想将此功能与非常大的列表一起使用。我打算用多个嵌套环的蛮力方式来做到这一点,但这非常慢。我想知道是否有更有效的方法可以执行此类任务。
这是一个快速的功能。在此功能中,每个句子都在n_tokens
-grams中损坏。将set()
包裹在ngrams
周围将确保仅包括不同的ngrams
,并且如果ngram
在句子中多次出现,则以后不会被双重计数。使用itertools
组合句子中的word_grams
,Counter
将计算每个ngram
的出现数量。最后,评估了gram_occur
的计数,以查看最频繁的革兰氏发生。结果将转换为符合您条件的字符串列表。
from nltk import ngrams
import itertools
from collections import Counter
def count_ngrams(l, n_tokens, min_occur):
word_grams = [set(ngrams(s.split(), n_tokens)) for s in l]
gram_occur = Counter(itertools.chain.from_iterable(word_grams))
return [" ".join([*words]) for (words, n) in gram_occur.items() if n >= min_occur]