简体   繁体   中英

error TypeError: 'str' object is not callable python

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

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM