我的代码中出现此错误,我不明白如何修复
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(' '))
中的
s.append(' '.join(str(i) for i in ngram))
TypeError:'str'对象不可调用
答案 0 :(得分:3)
您发布的代码是正确的,并且可以使用python 2.7和3.6(对于3.6,您必须在print语句周围添加括号)。但是,代码有3个空格缩进,应固定为4个空格。
此处如何重现您的错误
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
必须在某处将 str builtin 运算符重新定义为 str值,如上例所示。
这是同一问题的浅层示例
a = 'foo'
a()
Traceback (most recent call last):
File "python", line 2, in <module>
TypeError: 'str' object is not callable
答案 1 :(得分:1)
我通过运行代码获得输出。
O/P:
['one', 'two', 'three', 'four', 'one two', 'two three', 'three four', 'one two three', 'two three four']
我猜错误不会来。这是你期待的吗?