error TypeError: 'str' object is not calla

2019-08-22 14:14发布

问题:

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?