あなたの質問は、さまざまな理由で漠然としています。1 つには、タイトルは実際にはもっと適切に表現できます。あなたは自分が何をしたいのかをうまく説明していません。また、「最初の 10 個のバイグラム」とは、文字通り、テキスト内の最初のバイグラムを意味するのでしょうか、それとも最も頻繁に使用される 10 個のバイグラムを意味するのでしょうか? 後者だと思いましたが、そうでない場合は、並べ替えを削除して、テキストを最初の 11 語に制限してください。
from nltk.util import bigrams
from nltk import tokenize, pos_tag
from collections import defaultdict
counts = defaultdict(int)
counts_pos = defaultdict(int)
with open('twocities.txt') as f:
txt = f.read().lower()
txt = tokenize.word_tokenize(txt)
# Generate the lexical bigrams
bg = bigrams(txt)
# Do part-of-speech tagging and generate
# lexical+pos bigrams
pos = pos_tag(txt)
bg_pos = bigrams(pos)
# Count the number of occurences of each unique bigram
for bigram in bg:
counts[bigram] += 1
for bigram in bg_pos:
counts_pos[bigram] += 1
# Make a list of bigrams sorted on number of occurrences
sortedbigrams = sorted(counts, key = lambda x: counts[x], reverse=True)
sortedbigrams_pos = sorted(counts_pos, key = lambda x: counts_pos[x],
reverse=True)
# Remove bigrams that occur less than the given threshold
print 'Number of bigrams before thresholding: %i, %i' % \
(len(sortedbigrams), len(sortedbigrams_pos))
min_occurence = 2
sortedbigrams = [x for x in sortedbigrams if counts[x] > min_occurence]
sortedbigrams_pos = [x for x in sortedbigrams_pos if
counts_pos[x] > min_occurence]
print 'Number of bigrams after thresholding: %i, %i\n' % \
(len(sortedbigrams), len(sortedbigrams_pos))
# print results
print 'Top 10 lexical bigrams:'
for i in range(10):
print sortedbigrams[i], counts[sortedbigrams[i]]
print '\nTop 10 lexical+pos bigrams:'
for i in range(10):
print sortedbigrams_pos[i], counts_pos[sortedbigrams_pos[i]]
私の nltk インストールは Python 2.6 専用です。2.7 にインストールした場合は、 defaultdictの代わりにCounterを使用します。
A Tale Of Two Citiesの最初のページでこのスクリプトを使用すると、次の出力が得られます。
Top 10 lexical bigrams:
(',', 'and') 17
('it', 'was') 12
('of', 'the') 11
('in', 'the') 11
('was', 'the') 11
(',', 'it') 9
('and', 'the') 6
('with', 'a') 6
('on', 'the') 5
(',', 'we') 4
Top 10 lexical+pos bigrams:
((',', ','), ('and', 'CC')) 17
(('it', 'PRP'), ('was', 'VBD')) 12
(('in', 'IN'), ('the', 'DT')) 11
(('was', 'VBD'), ('the', 'DT')) 11
(('of', 'IN'), ('the', 'DT')) 11
((',', ','), ('it', 'PRP')) 9
(('and', 'CC'), ('the', 'DT')) 6
(('with', 'IN'), ('a', 'DT')) 6
(('on', 'IN'), ('the', 'DT')) 5
(('and', 'CC'), ('a', 'DT')) 4