NLP sentiment analysis: 'list' object has no attribute 'sentiment'

Viewed 1089

For a current project, I am planning to perform a sentiment analysis for a number of word combinations with TextBlob.

When running the sentiment analysis line polarity = common_words.sentiment.polarity and calling the results with print(i, word, freq, polarity), I am receiving the following error message:

polarity = common_words.sentiment.polarity
AttributeError: 'list' object has no attribute 'sentiment'

Is there any smart tweak to get this running? The corresponding code section looks like this:

for i in ['Text_Pro','Text_Con','Text_Main']:
    common_words = get_top_n_trigram(df[i], 150)
    polarity = common_words.sentiment.polarity
    for word, freq in common_words:
        print(i, word, freq, polarity)

Edit: Please find below the full solution for the situation (in accordance with discussions with user leopardxpreload):

for i in ['Text_Pro','Text_Con','Text_Main']:
    common_words = str(get_top_n_trigram(df[i], 150))
    polarity_list = str([TextBlob(i).sentiment.polarity for i in common_words])
    for element in polarity_list:
        print(i, element)
    for word, freq in common_words:
        print(i, word, freq)
1 Answers

It seems like you are trying to use the TextBlob calls on a list and not a TextBlob object.

for i in ['Text_Pro','Text_Con','Text_Main']:
    common_words = get_top_n_trigram(df[i], 150)
    # Not sure what is in common_words, but it needs to be a string
    polarity = TextBlob(common_words).sentiment.polarity
    for word, freq in common_words:
        print(i, word, freq, polarity)

If common_words is a list you might need to add:

polarity_list = [TextBlob(i).sentiment.polarity for i in common_words]

Possible copy-paste solution:

for i in ['Text_Pro','Text_Con','Text_Main']:
    common_words = get_top_n_trigram(df[i], 150)
    polarity_list = [TextBlob(i).sentiment.polarity for i in common_words]
    for element in polarity_list:
        print(i, element)
Related