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

Viewed 4658

I'm trying to generate a Latent Dirichlet Allocation model using 500 different txts. One part of my code is as follows:

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)

And it gives me the following error:

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

Can someone fix it for me? Thanks!

2 Answers

Welcome to Stackoverflow.

Python is telling you that docs[idx] is not a list, but a string. Therefore it has no append() method for you to call.

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

If all you want to do is add your token string to your docs[idx] string then use '+':

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

If it's more complicated then that's a different matter.

Related