error TypeError: 'str' object is not callable python
error TypeError: 'str' object is not callable 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(' '))
错误
s.append(' '.join(str(i) for i in ngram))
类型错误:'str'对象不可调用
我通过 运行 你的代码得到输出。
O/P:
['one', 'two', 'three', 'four', 'one two', 'two three', 'three four', 'one two three', 'two three four']
估计不会出现错误。这是你期待的吗?
您发布的代码是正确的并且适用于 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 内置 运算符重新定义为 str 值 ,如上例所示。
这里是同一问题的一个较浅的例子
a = 'foo'
a()
Traceback (most recent call last):
File "python", line 2, in <module>
TypeError: 'str' object is not callable
我的代码中有这个错误,我不知道如何修复
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))
类型错误:'str'对象不可调用
我通过 运行 你的代码得到输出。
O/P:
['one', 'two', 'three', 'four', 'one two', 'two three', 'three four', 'one two three', 'two three four']
估计不会出现错误。这是你期待的吗?
您发布的代码是正确的并且适用于 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 内置 运算符重新定义为 str 值 ,如上例所示。
这里是同一问题的一个较浅的例子
a = 'foo'
a()
Traceback (most recent call last):
File "python", line 2, in <module>
TypeError: 'str' object is not callable