首页 > 解决方案 > 为什么我在 Python 中收到“AttributeError:'str' object has no attribute 'append'”?

问题描述

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

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'

有人可以帮我修一下吗?谢谢!

标签: pythonmodellda

解决方案


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

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

或者:

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


推荐阅读