错误类型错误:“str”对象不可调用python

2024-05-19 01:05:04 发布

您现在位置: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))

TypeError:“str”对象不可调用


Tags: 代码inimportforminmaxwordwords
2条回答

您发布的代码是正确的,并且可以同时使用Python2.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 value,如上面的示例所示。

这里是同一问题的一个较浅的例子

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

我通过运行你的代码得到输出。

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

我想错误不会来的。这是你想要的吗?

相关问题 更多 >

    热门问题