2012-10-10 3 views
11

クラシファイアの機能としてngramカウントを使用した論文を読んだことがあります。これは正確に何を意味しているのでしょうか。ngramカウントとは何ですか?nltkを使用して実装する方法は?

例のテキスト:

を「Loremのイプサム悲しみはsedのDIAM、AMET conseteturのsadipscingのelitrに座る」私はどの「レベルで定義する必要があり、このテキストのうちのユニグラム、バイグラム、トライグラムなどを作成することができますこれらのユニグラムを作成する。 "レベル"は、文字、音節、単語...

上記の文章からunigramsを作成すると、単純にすべての単語のリストが作成されます。

バイグラムを作成すると、単語のペアが互いに続く単語を結びつけます。

もしngramカウントについて話をするならば、テキストからunigrams、bigrams、trigramsなどを作成し、ngramの発生頻度を数えます。

Pythonのnltkパッケージに既存のメソッドがありますか?それとも自分のバージョンを実装する必要がありますか?

+1

ユアーズは、一般的な解釈であるが、「グラム」単位は、例えば可能性があなたの時間の複雑さOを与えますバイトまたは文字でもあります。したがって、スライディングウィンドウを使用する場合、 "lorem"の文字3グラムは "lor"と "em"または "lor"、 "ore"、 "rem"になります。 – tripleee

答えて

15

私の古いコードが見つかりました。おそらく便利です。

import nltk 
from nltk import bigrams 
from nltk import trigrams 

text="""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ornare 
tempor lacus, quis pellentesque diam tempus vitae. Morbi justo mauris, 
congue sit amet imperdiet ipsum dolor sit amet, consectetur adipiscing elit. Nullam ornare 
tempor lacus, quis pellentesque diam""" 
# split the texts into tokens 
tokens = nltk.word_tokenize(text) 
tokens = [token.lower() for token in tokens if len(token) > 1] #same as unigrams 
bi_tokens = bigrams(tokens) 
tri_tokens = trigrams(tokens) 

# print trigrams count 

print [(item, tri_tokens.count(item)) for item in sorted(set(tri_tokens))] 
>>> 
[(('adipiscing', 'elit.', 'nullam'), 2), (('amet', 'consectetur', 'adipiscing'), 2),(('amet', 'imperdiet', 'ipsum'), 1), (('congue', 'sit', 'amet'), 1), (('consectetur', 'adipiscing', 'elit.'), 2), (('diam', 'tempus', 'vitae.'), 1), (('dolor', 'sit', 'amet'), 2), (('elit.', 'nullam', 'ornare'), 2), (('imperdiet', 'ipsum', 'dolor'), 1), (('ipsum', 'dolor', 'sit'), 2), (('justo', 'mauris', 'congue'), 1), (('lacus', 'quis', 'pellentesque'), 2), (('lorem', 'ipsum', 'dolor'), 1), (('mauris', 'congue', 'sit'), 1), (('morbi', 'justo', 'mauris'), 1), (('nullam', 'ornare', 'tempor'), 2), (('ornare', 'tempor', 'lacus'), 2), (('pellentesque', 'diam', 'tempus'), 1), (('quis', 'pellentesque', 'diam'), 2), (('sit', 'amet', 'consectetur'), 2), (('sit', 'amet', 'imperdiet'), 1), (('tempor', 'lacus', 'quis'), 2), (('tempus', 'vitae.', 'morbi'), 1), (('vitae.', 'morbi', 'justo'), 1)] 
+0

あなたのコードをありがとう! – akohout

+0

彼らは同じ文章ではないなら、['tempus'、 'vitae'、 'morbi']をトリグラムとして数えるのは正しいですか? – Mouscellaneous

-1

これを助ける特定の方法がnltkにはないと思います。しかしこれは難しいことではありません。 n語の文がある場合(単語レベルを使用していると仮定して)、長さ1-nのすべてのnグラムを取得し、それらのnグラムごとに反復し、値をカウントとして連想配列のキーにします。 30行以上のコードでなければならない場合は、独自のパッケージを作成して必要な場所にインポートすることができます。

+1

それでは、ngramのことを正しく理解しているようです。 – akohout

2

nグラムを数えるときは、カウントを使用するのではなく、ハッシュテーブル(辞書)を使用する方がよいでしょう。上記の例の場合:

unigrams = {} 
for token in tokens: 
    if token not in unigrams: 
    unigrams[token] = 1 
    else: 
    unigrams[token] += 1 

これは、(n)は

+1

これは答えですか?もしそうなら、それを詳細と一緒に投稿してください。 – Sachith

関連する問題