2016-07-11 5 views
1

nltk.Textモジュールのtext.similar('example')関数を使用しています。nltkで関数をオーバーライドする - ContextIndexクラスのエラー

(どのプリントコーパスに基づいて、指定された単語のための類似した単語。)

私は、リスト内の単語のリストを保存したいが。しかし、関数自体はNoneを返します。

#text is a variable of nltk.Text module 
simList = text.similar("physics") 
>>> a = text.similar("physics") 
the and a in science this which it that energy his of but chemistry is 
space mathematics theory as mechanics 
>>> a 
>>> a 
# a contains no value. 

ソース機能自体を変更する必要がありますか?しかし、私はそれが良い習慣だとは思わない。どうすればその関数をオーバーライドして値を返すことができますか?

編集 - this threadを参照して、私はContextIndexクラスを使ってみました。しかし、私は次のエラーが発生しています。

File "test.py", line 39, in <module> 
    text = nltk.text.ContextIndex(word.lower() for word in words) File "/home/kenden/den/codes/nlpenv/local/lib/python2.7/site-packages/nltk/text.py", line 56, in __init__ 
    for i, w in enumerate(tokens)) File "/home/kenden/den/codes/nlpenv/local/lib/python2.7/site-packages/nltk/probability.py", line 1752, in __init__ 
    for (cond, sample) in cond_samples: File "/home/kenden/den/codes/nlpenv/local/lib/python2.7/site-packages/nltk/text.py", line 56, in <genexpr> 
    for i, w in enumerate(tokens)) File "/home/kenden/den/codes/nlpenv/local/lib/python2.7/site-packages/nltk/text.py", line 43, in _default_context 
    right = (tokens[i+1].lower() if i != len(tokens) - 1 else '*END*') TypeError: object of type 'generator' has no len() 

は、これは私がこの問題を解決するにはどうすればよいtest.py

text = nltk.text.ContextIndex(word.lower() for word in words) 

の私のライン39のですか?

+3

可能な重複[変数とText.similarを()NLTK保存方法](http://stackoverflow.com/questions/10537720/how-:問題を回避するには、ちょうど真のリスト、例えばを渡します保存するnltk-text-like-with-variable) –

答えて

1

ContextIndexコンストラクタがトークンリストのlen()(引数tokens)を取得しようとしているため、エラーが発生しています。しかし、実際にはそれをジェネレータとして渡すため、エラーが発生します。

text = nltk.text.ContextIndex(list(word.lower() for word in words))