临近毕业答辩,有些人毕设还没怎么写,找我帮忙几小时完成知乎问答爬取和情感分析功能。爬虫一小时左右就写好并爬取完数据存到 CSV 里,但情感分析怎么能几小时内完成。我研究方向是 CV,对 NLP 的了解只限于 transfomer 和常用模型的名词,但四年的室友我还是得帮个忙。
我首先想到的是否有现成的 Python 库可以调用,因为赶时间所以不能涉及自定义词典、模型训练等花费时间长的工作,能直接用几行代码得出预测值。最后锁定了 SnowNLP 和 Cemotion。SnowNLP 用的是经典机器学习的贝叶斯算法,但已经有七年没有更新了;Cemotion 使用的是深度学习 RNN 模型,最近更新时间也比较近。在未经训练的情况下简单试用后 Cemotion 的预测准确率略高于 SnowNLP。
Cemotion 通过 pip 安装即可,但涉及 TensorFlow 等库且要下载 RNN 模型,我在 Colab 环境上下载模型花了 47s,建议使用国内镜像安装。
pip install Cemotion | |
# or 清华源 | |
pip install Cemotion -i https://pypi.tuna.tsinghua.edu.cn/simple |
安装好之后就通过 pandas 读取 CSV 文件中的回答并对其进行情感分析,将结果写入新的 CSV 文件中。完整代码如下:
# 导入相关库 | |
import os | |
import csv | |
import pandas as pd | |
from cemotion import Cemotion | |
def get_result(file_path): | |
predict = [] | |
data = pd.read_csv(file_path) | |
answers = data['回答的内容'] | |
answers = [str(a) for a in list(answers)] | |
c = Cemotion() | |
predict = c.predict(answers) | |
return predict | |
def out_to_csv(datas): | |
header = ['answer','predict'] | |
with open('./predict_result.csv', 'a', newline='',encoding='utf-8') as f: | |
writer = csv.DictWriter(f,fieldnames=header) | |
writer.writeheader() # 写入列名 | |
for i in range(len(datas)): | |
writer = csv.writer(f) | |
writer.writerow(datas[i]) | |
f.close() | |
file_path = './result.csv' | |
results = get_result(file_path) | |
for result in results: | |
print('"', result[0] , '"\n' , '预测值:{:6f}'.format(result[1]) , '\n') | |
# 写入到 CSV 文件 | |
out_to_csv(results) |
几个小时完成的情感分析过于粗糙,预测值和个人对回答的实际感受有些误差,但应付毕设应该足够,之后就是对这些数据放到 web 页面可视化。
最后希望毕设不要赶 ddl 才写,真的对延毕无所谓吗。