【问题标题】:error TypeError: 'str' object is not callable python错误TypeError:'str'对象不可调用python
【发布时间】:2017-12-03 03:32:01
【问题描述】:

我的代码中有这个错误,我不知道如何修复

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' 对象不可调用

【问题讨论】:

  • 你定义了一个使用str作为变量名的字符串吗?
  • 你在哪里定义了一个名为str的变量?

标签: python python-2.7 nltk n-gram


【解决方案1】:

您发布的代码是正确的,并且适用于 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 builtin 运算符重新定义为 str value,如上例所示。

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

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

【讨论】:

    【解决方案2】:

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

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

    我想错误不会出现。这是你所期望的吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2013-08-05
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多