【问题标题】:How to display the sentiment analysis values in a pie chart using matplotlib in python 3.6?如何在 python 3.6 中使用 matplotlib 在饼图中显示情绪分析值?
【发布时间】:2019-01-20 11:42:38
【问题描述】:

主要目标是在饼图中显示任何用户输入的正面、负面和中性的情绪分析值。虽然代码没有错误,但饼图仅将中性值显示为整个图表的 100%,即使在输入负数或正数作为输入后,也将输入分类为中性。

我尝试修改条件语句并在 Textblob 中传递主输入变量本身。然而,预期的结果并没有产生。

from textblob import TextBlob
import matplotlib.pyplot as plt

def percentage(part,whole):
    return 100*float(part)/float(whole)


inp = input("Enter something:")

positive = 0
negative = 0
neutral = 0
polarity = 0


for word in inp:
    analyzer = TextBlob(word)
    polarity += analyzer.sentiment.polarity
    if analyzer.sentiment.polarity > 0:
    positive += 1
    elif analyzer.sentiment.polarity < 0:
    negative += 1
    elif analyzer.sentiment.polarity == 0:
    neutral += 1

positive = percentage(positive,(positive + negative + neutral))
negative = percentage(negative,(positive + negative + neutral))
neutral = percentage(neutral,(positive + negative + neutral))

positive = format(positive,'.2f')
negative = format(negative,'.2f')
neutral = format(neutral,'.2f')

if (polarity > 0):
    print("Positive")
elif (polarity < 0):
    print("Negative")
elif (polarity == 0):
    print("Neutral")

labels = ['Positive ['+str(positive)+'%]', 'Negative ['+str(negative)+'%]', 
'Neutral ['+str(neutral)+'%]']
sizes = [positive, negative, neutral]
colors = ['blue','red','yellow']
patches, texts = plt.pie(sizes, colors=colors, startangle=90)
plt.legend(patches,labels,loc="best")
plt.title("Polarity Pie Chart")
plt.axis('equal')
plt.tight_layout()
plt.show()

Expected 输出是正确分类并在饼图中显示正、负和中性。但是输出,无论输入的上下文如何,都只分类为中性,饼图也只显示中性。

【问题讨论】:

  • 如果您打印sizes,它是否包含“正”或“负”的任何非零值?如果不是,这和matplotlib有什么关系?
  • @ImportanceOfBeingErnest 我使用 matplotlib 生成饼图 w.r.t 到百分比组成。关于正负的非零值,你能更具体一点吗?我增加了它们的值,并尝试使用不同的变量作为百分比。没有改进。
  • 这是 matplotlib 问题还是 textblob 问题?通过print(sizes) 查找并判断这是否是您所期望的。
  • @ImportanceOfBeingErnest 也尝试过。它只打印公式化的正值、负值和中性值,其中正值和负值没有被计算。
  • 所以它与绘图无关。我怀疑 textblob 认为单个字符是中性的。也许您希望它计算整个单词的情绪?

标签: python-3.x matplotlib nlp sentiment-analysis textblob


【解决方案1】:

positive = format(positive,'.2f') ....这个语句把数字转换成字符串, ..所以当您与" if (polarity &gt; 0) --&gt; print("Positive")" 进行比较时,它会作为字符串进行比较..

重做为" positive = float(format(positive, '.2f'))

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    相关资源
    最近更新 更多