error TypeError: 'str' object is not callable python

瘦欲@ 提交于 2019-12-12 04:43:19

问题


I have this error in my code and I don't understand how to fixed

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 in

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

TypeError: 'str' object is not callable


回答1:


The code you posted is correct and work with both python 2.7 and 3.6 (for 3.6 you have to put parenthesis around the print statement). However, the code as is has a 3 spaces indent which should be fixed to 4 spaces.

here how to reproduce your error

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

There must be somewhere where you redefine str builtin operator as a str value like the example above.

Here a shallower example of the same problem

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



回答2:


I get the output by running your code.

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

I guess error won't come. Is this you expect?



来源:https://stackoverflow.com/questions/47614975/error-typeerror-str-object-is-not-callable-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!