2017-12-03 13 views
0

ではありません、私は私のコードでこのエラーを持っていると私はエラー例外TypeError: 'strの' オブジェクトが呼び出し可能なPythonの

import nltk 
from nltk.util import ngrams 


def word_grams(words, min=1, max=4): 
    s = [] 
    for n in range(min, max): 
     for ngram in ngrams(words, n): 
      s.append(' '.join(str(i) for i in ngram)) 
    return s 

print word_grams('one two three four'.split(' ')) 

erorr

s.append(' '.join(str(i) for i in ngram)) 

ではTypeError固定する方法を理解していない:「STRを'オブジェクトは呼び出し可能ではありません

+3

の浅い例は、変数名として 'str'を使用して文字列を定義しましたか? – abccd

+2

'str'という変数をどこで定義しましたか? –

答えて

2

投稿したコードは正しく、python 2.7と3.6(3.6の場合は、print文の前後にかっこを入れてください)で動作します。しかし、コードasは3スペースインデントを持ち、これは4スペースに固定する必要があります。あなたのエラー、あなたが上記の例のようにstrの値としてstrの組み込みオペレータを再定義するところ

s = [] 
str = 'overload str with string' 
# The str below is a string and not function, hence the error 
s.append(' '.join(str(x) for x in ['a', 'b', 'c'])) 
print(s) 

Traceback (most recent call last): 
    File "python", line 4, in <module> 
    File "python", line 4, in <genexpr> 
TypeError: 'str' object is not callable 

がどこかに存在する必要がありますを再現する方法をここに

。ここで

同じ問題

a = 'foo' 
a() 
Traceback (most recent call last): 
    File "python", line 2, in <module> 
TypeError: 'str' object is not callable 
1

コードを実行して出力を取得します。

O/P: 
['one', 'two', 'three', 'four', 'one two', 'two three', 'three four', 'one two three', 'two three four'] 

エラーは表示されません。これはあなたの期待ですか?

関連する問題