Why am I getting "AttributeError: 'str' object has no attribute 'append'" in Python?

Why am I getting "AttributeError: 'str' object has no attribute 'append'" in Python?

我正在尝试使用 500 种不同的文本文件生成 Latent Dirichlet Allocation 模型。 我的一部分代码如下:

from gensim.models import Phrases
from gensim import corpora, models

bigram = Phrases(docs, min_count=10)
trigram = Phrases(bigram[docs])
for idx in range(len(docs)):
    for token in bigram[docs[idx]]:
        if '_' in token:
            # Token is a bigram, add to document.
            docs[idx].append(token)
    for token in trigram[docs[idx]]:
        if '_' in token:
            # Token is a bigram, add to document.
            docs[idx].append(token)

它给了我以下错误:

File ".../scriptLDA.py", line 74, in <module>
    docs[idx].append(token)
AttributeError: 'str' object has no attribute 'append'

有人可以帮我修好吗? 谢谢!

欢迎使用 Whosebug。

Python 告诉你 docs[idx] 不是一个列表,而是一个字符串。因此它没有 append() 方法供你调用。

>>> fred = "blah blah"
>>> fred.append("Bob")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
>>> elsie = [1,2,3,4]
>>> elsie.append(5)
>>> elsie
[1, 2, 3, 4, 5]
>>> type(fred)
<class 'str'>
>>> type(elsie)
<class 'list'>
>>> 

如果您只想将您的令牌字符串添加到您的文档[idx] 字符串中,然后使用'+':

>>> ginger = fred + "Another string"
>>> ginger
'blah blahAnother string'

如果更复杂那就另当别论了。

append() 用于向数组添加元素,而不是连接字符串。 https://docs.python.org/3/tutorial/datastructures.html 你可以这样做:

a = "string1" a = a + "string2"

或:

a = [1,2,3,4] a.append(5)