You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.1 KiB
68 lines
2.1 KiB
2 months ago
|
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()
|