为什么在Python中出现“ AttributeError:'str'对象没有属性'append'?”

问题描述 投票:0回答:1

我正在尝试使用500个不同的txt生成潜在Dirichlet分配模型。我的代码的一部分如下:

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'

有人可以为我修复它吗?谢谢!

python model lda
1个回答
0
投票

欢迎使用Stackoverflow。

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'>
>>> 

如果您只想将令牌字符串添加到docs [idx]字符串中,请使用'+':

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

如果更复杂,那是另一回事。

© www.soinside.com 2019 - 2024. All rights reserved.