次のようなものになりたいですそのために簡単にCounter
を使用できます。 nは -gramsをカウントするための一般的な機能は以下の通りです:
from collections import Counter
from itertools import islice
def count_ngrams(iterable,n=2):
return Counter(zip(*[islice(iterable,i,None) for i in range(n)]))
これが生成します。
>>> count_ngrams(['hello', 'how', 'are', 'you', 'doing', 'today', 'are', 'you', 'okay'],2)
Counter({('are', 'you'): 2, ('doing', 'today'): 1, ('you', 'doing'): 1, ('you', 'okay'): 1, ('today', 'are'): 1, ('how', 'are'): 1, ('hello', 'how'): 1})
>>> count_ngrams(['hello', 'how', 'are', 'you', 'doing', 'today', 'are', 'you', 'okay'],3)
Counter({('are', 'you', 'okay'): 1, ('you', 'doing', 'today'): 1, ('are', 'you', 'doing'): 1, ('today', 'are', 'you'): 1, ('how', 'are', 'you'): 1, ('doing', 'today', 'are'): 1, ('hello', 'how', 'are'): 1})
>>> count_ngrams(['hello', 'how', 'are', 'you', 'doing', 'today', 'are', 'you', 'okay'],4)
Counter({('doing', 'today', 'are', 'you'): 1, ('today', 'are', 'you', 'okay'): 1, ('are', 'you', 'doing', 'today'): 1, ('how', 'are', 'you', 'doing'): 1, ('you', 'doing', 'today', 'are'): 1, ('hello', 'how', 'are', 'you'): 1})
「カウンター」はどうですか? –
タプルと一致するようにトークンがリスト内で隣り合っていなければなりませんか? – chbchb55
@ chbchb55:多かれ少なかれ、* n *グラムの考えです。 –