如何利用 Python 的 SnowNLP 分析用户评论情绪并自动生成词云?
解读
面试官抛出此题,表面考察“会不会用两个库”,实质是在验证候选人三方面的技术文档能力:
- 需求澄清与场景还原——能否把“情绪+词云”这一模糊需求拆成可落地的数据、指标、交付物;
- 工具链与合规意识——是否知道 SnowNLP 只支持中文、情感值是 0–1 概率、词云默认过滤不严,能否在代码里提前做脱敏、去隐私、去停用词;
- 文档闭环——跑通代码后,能否输出一份“复制即可用”的脚本、一份指标说明、一张可视化图,以及后续接入 CI/CD 的扩展方案。
国内面试节奏快,回答时必须先给“最小可运行示例”,再补“工程化细节”,否则会被判定为“纸上谈兵”。
知识点
- SnowNLP 情感模型原理:基于淘宝评论训练好的朴素贝叶斯,返回 0–1 概率,>0.5 视为正向;缺点是对领域词汇、网络新词、讽刺句识别弱。
- 中文文本预处理:正则去 @ 提及、URL、emoji、身份证号、手机号;用 jieba 精确模式 + 自定义用户词典;停用词表必须包含“不错、满意、好评”等电商水军高频词,否则词云会被无意义词占据。
- 词云合规:font_path 必须指向开源可商用字体(如思源黑体),禁止用 Windows 自带微软雅黑;background_color 建议设白色方便打印;collocations=False 避免重复搭配。
- 数据安全:若评论来自线上日志,需先脱敏再落盘;脚本里禁止打印原始昵称、手机号;最终交付物建议用 PDF 或 PNG,避免 Excel 二次编辑泄露。
- 文档输出规范:脚本头部加 # -- coding: utf-8 --,注释里写清依赖版本;README 中给出“一键安装 requirements.txt”命令;在运维手册里说明“每日凌晨跑批,输出 sentiment_report_yyyymmdd.png,上传至内网 Confluence”。
答案
下面给出可直接落地的最小工程,分为三段:脚本、指标说明、接入建议。候选人现场可在白板上先写核心 20 行,再口述扩展。
# -*- coding: utf-8 -*-
"""
用户评论情绪分析&词云自动生成脚本
依赖:snownlp、jieba、wordcloud、pandas、matplotlib
运行:python sentiment_wordcloud.py --input comments.txt --output_dir ./report
"""
import re, os, jieba, argparse, pandas as pd
from snownlp import SnowNLP
from wordcloud import WordCloud
import matplotlib.pyplot as plt
STOPWORDS = set(open('stopwords.txt', encoding='utf-8').read().split())
FONT_PATH = 'SourceHanSansCN-Regular.otf' # 思源黑体,开源可商用
def clean(text):
text = re.sub(r'[\d\w._%+-]+@[\d\w.-]+\.[\w]{2,4}', '', text) # 去邮箱
text = re.sub(r'1[3-9]\d{9}', '', text) # 去手机号
text = re.sub(r'http\S+', '', text) # 去URL
return text.strip()
def sentiment_score(txt):
s = SnowNLP(txt)
return s.sentiments
def gen_wordcloud(text_series, save_path):
words = jieba.lcut(' '.join(text_series), cut_all=False)
words = [w for w in words if w not in STOPWORDS and len(w) > 1]
txt = ' '.join(words)
wc = WordCloud(font_path=FONT_PATH, width=1200, height=600,
background_color='white', collocations=False).generate(txt)
wc.to_file(save_path)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input', required=True, help='原始评论文件,每行一条')
parser.add_argument('--output_dir', required=True, help='输出目录')
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
df = pd.read_csv(args.input, names=['raw'], sep='\t', encoding='utf-8')
df['clean'] = df['raw'].apply(clean)
df['score'] = df['clean'].apply(sentiment_score)
df['label'] = df['score'].apply(lambda x: 'pos' if x > 0.5 else 'neg')
# 输出指标
summary = {
'总条数': len(df),
'正向占比': f"{(df['label']=='pos').mean():.2%}",
'平均情感分': f"{df['score'].mean():.3f}"
}
with open(os.path.join(args.output_dir, 'summary.txt'), 'w', encoding='utf-8') as f:
for k, v in summary.items():
f.write(f"{k}\t{v}\n")
# 分别生成正负词云
gen_wordcloud(df[df['label']=='pos']['clean'],
os.path.join(args.output_dir, 'pos_wordcloud.png'))
gen_wordcloud(df[df['label']=='neg']['clean'],
os.path.join(args.output_dir, 'neg_wordcloud.png'))
if __name__ == '__main__':
main()
口述要点:
- 脚本跑完后,report 目录下会有 summary.txt、pos_wordcloud.png、neg_wordcloud.png,可直接贴到 Confluence;
- 若评论量>10 万,先把 SnowNLP 换成多进程或 batch 推理,否则单进程 CPU 跑满;
- 对讽刺、反语,可额外接入百度 EasyDL 自训练模型,把结果写进“高级版报告”,原脚本留作“快速版报告”,实现分级交付。
拓展思考
- 版本管理:把脚本、stopwords、字体、sample 数据一起放进 GitLab,CI 里加 flake8 检查与单元测试(pytest 判断 df 不为空、png 文件大小>0)。
- 自动化闭环:Jenkins 每日拉取 Elasticsearch 前日评论索引→跑脚本→推送飞书群卡片,卡片里带 summary 指标与词云缩略图,一线客服可点击“查看大图”。
- 多语言场景:SnowNLP 仅支持中文,若公司业务出海,可抽象 BaseSentiment 类,底层同时接入 SnowNLP(zh)、TextBlob(en)、Cabocha(ja),通过 langdetect 自动路由,文档侧只需维护一份“情绪分析插件说明书”。
- 安全合规:评论含用户 UID 时需做哈希映射,脚本里加盐值;最终报告禁止出现原始 UID,防止“通过词云+时间戳”反推用户。
- 性能与成本:SnowNLP 每次初始化会加载模型,10 万条评论内存峰值约 1.2 GB;如预算充足,可转用 PaddleNLP 轻量模型 GPU 推理,时延从 2 h 降到 5 min,技术文档需同步更新“部署资源清单”与“预算对比表”,供领导审批。