【问题标题】:NLP sentiment analysis: 'list' object has no attribute 'sentiment'NLP 情感分析:“列表”对象没有“情感”属性
【发布时间】:2020-06-10 09:15:44
【问题描述】:

对于当前的项目,我计划使用 TextBlob 对多个单词组合进行情绪分析。

当运行情感分析行polarity = common_words.sentiment.polarity 并使用 print(i, word, freq, polar) 调用结果时,我收到以下错误消息:

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

是否有任何聪明的调整来让它运行?对应的代码部分如下所示:

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)

编辑:请在下面找到该情况的完整解决方案(根据与用户 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)

【问题讨论】:

  • common_wordslist,而不是具有sentiment 函数的对象。

标签: python nlp sentiment-analysis textblob


【解决方案1】:

您似乎正在尝试对列表而不是 TextBlob 对象使用 TextBlob 调用。

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)

如果common_words 是您可能需要添加的列表:

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

可能的复制粘贴解决方案:

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)

【讨论】:

  • 是的,所以你有一个列表并且TextBlob 函数only 接受一个字符串——在初始化变量之后执行print(common_words),你应该会看到一个输出方括号。
  • 另外,我认为尝试for word, freq in common_words 会导致“解包问题” - 您需要先进行for element in comon_words 然后进行索引:element[1] .. 等等。
  • # 注释掉common_words = ...下面的所有内容
  • 是的,但打印出来的是什么?
  • 我通过将 common_words 和 polar_list 定义为字符串来使其工作。将在其他用户的问题文本中突出显示这一点。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多