From 8d95536c541a35f7b8409a40741644143fa347de Mon Sep 17 00:00:00 2001 From: pufahrcyp <1195744232@qq.com> Date: Wed, 18 Sep 2024 22:07:47 +0800 Subject: [PATCH] =?UTF-8?q?ADD=20=E9=99=84=E5=8A=A0=EF=BC=9A=E6=83=85?= =?UTF-8?q?=E6=84=9F=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- emotion_analysis.py | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 emotion_analysis.py diff --git a/emotion_analysis.py b/emotion_analysis.py new file mode 100644 index 0000000..5decf74 --- /dev/null +++ b/emotion_analysis.py @@ -0,0 +1,68 @@ +from snownlp import SnowNLP +import matplotlib.pyplot as plt +import os +# search_word = "2024巴黎奥运会" + +def emotion_aly(search_word): + print("正在进行弹幕情感分析...") + + # 定义文件名 + file_name = f'{search_word}弹幕.txt' + + # 若文件不存在则停止执行 + if not os.path.exists(file_name): + print(f"文件 {file_name} 不存在。") + return + + # 初始化空列表 + comment_list = [] + + # 读取文件并将每一行数据添加到列表 + with open(file_name, mode='r', encoding='utf-8') as f: + comment_list = f.readlines() + + # 去除每行末尾的换行符 + comment_list = [comment.strip() for comment in comment_list] + + # 初始化情感统计 + emotions = { + 'positive': 0, + 'negative': 0, + 'neutral': 0 + } + + # 若文件为空则停止执行 + if not comment_list: + print("弹幕文件为空,无法进行情感分析。") + return + + # 对每条评论进行情感分析 + for comment in comment_list: + s = SnowNLP(comment) + if s.sentiments > 0.7: + emotions['positive'] += 1 + elif s.sentiments < 0.3: + emotions['negative'] += 1 + else: + emotions['neutral'] += 1 + + print(emotions) + + # 防止饼状图数据为0的情况 + if sum(emotions.values()) == 0: + print("没有有效的情感分析数据。") + return + + # 绘制饼状图 + colors = ['#ff9999', '#66b3ff', '#99ff99'] + plt.style.use('fivethirtyeight') + plt.pie(emotions.values(), labels=emotions.keys(), colors=colors, autopct='%1.1f%%') + # 调整子图的边距 + plt.subplots_adjust(top=0.901, bottom=0.044, left=0.033, right=0.967, hspace=0.2, wspace=0.2) + plt.tight_layout() + plt.rcParams['font.family'] = ['sans-serif'] + plt.rcParams['font.sans-serif'] = ['SimHei'] + plt.rcParams['font.size'] = 14 + plt.title(f"{search_word}弹幕情感分析图", fontsize=16) + plt.savefig(f"{search_word}弹幕情感分析图.jpg") + plt.show() \ No newline at end of file