早く、簡単に共起語ペアの頻度を数える

やりたいこと

共起語ペアのカウントを取りたい。

単に基礎集計をやりたいだけなので、matrixを作る必要はない。

解決策

タプルで共起語ペアを作って、カウントする

手順は

  1. 共起語のタプルを作って、リストに放り込んでいく
  2. collection::Counter.most_common()で頻度とる(条件つきで頻度を知りたいときは、NLTK::ConditionalFreqDist)
# 共起語カウントをする方法
test_sent_list = ['I', 'am', 'so', 'happy', 'I', 'am', 'a', 'girl', 'with', 'golden', 'hair', '.']

# 文中の共起語のタプルペアをつくる
def tessa(source):
    result = []
    for p1 in range(len(source)):
        for p2 in range(p1+1,len(source)):
            result.append( (source[p1],source[p2]) )
            
    return result


list_res = tessa(test_sent_list)

#  単純にペアの頻度を知るだけなら、collections::Counter.most_common()を使う
from collections import Counter
counter_res = Counter(list_res)
print counter_res.most_common()

print '-'* 20
# 条件つけて頻度を知りたいときは、NLTK::ConditionalFreqDist.most_common()にする
cfd = nltk.ConditionalFreqDist(list_res)
print cfd['I'].most_common()

結果は

[(('I', 'am'), 3), (('am', '.'), 2), (('am', 'golden'), 2), (('I', 'with'), 2), (('am', 'hair'), 2), (('I', 'girl'), 2), (('I', '.'), 2), (('I', 'a'), 2), (('am', 'a'), 2), (('I', 'hair'), 2), (('I', 'golden'), 2), (('am', 'girl'), 2), (('am', 'with'), 2), (('girl', '.'), 1), (('so', 'girl'), 1), (('am', 'so'), 1), (('with', 'hair'), 1), (('so', 'happy'), 1), (('happy', 'hair'), 1), (('happy', '.'), 1), (('with', '.'), 1), (('so', 'am'), 1), (('hair', '.'), 1), (('happy', 'I'), 1), (('a', '.'), 1), (('golden', 'hair'), 1), (('so', 'golden'), 1), (('happy', 'girl'), 1), (('so', 'a'), 1), (('a', 'golden'), 1), (('am', 'happy'), 1), (('a', 'hair'), 1), (('so', 'I'), 1), (('so', '.'), 1), (('happy', 'a'), 1), (('am', 'I'), 1), (('happy', 'with'), 1), (('am', 'am'), 1), (('a', 'girl'), 1), (('girl', 'with'), 1), (('I', 'happy'), 1), (('I', 'so'), 1), (('happy', 'am'), 1), (('with', 'golden'), 1), (('so', 'with'), 1), (('a', 'with'), 1), (('so', 'hair'), 1), (('girl', 'hair'), 1), (('girl', 'golden'), 1), (('golden', '.'), 1), (('I', 'I'), 1), (('happy', 'golden'), 1)]
--------------------
[('am', 3), ('a', 2), ('golden', 2), ('.', 2), ('hair', 2), ('girl', 2), ('with', 2), ('I', 1), ('so', 1), ('happy', 1)]