← 返回教程目录
第 2 章 · 第 2 节 情感分析

SnowNLP:Python 中文情感分析首选

SnowNLP: The Go-To Python Sentiment Lib

SnowNLP 是 Python 中文情感分析最常用的库 — 基于朴素贝叶斯训练,单条评分只要 1ms。

1. 安装

pip install snownlp

2. 单条评论打分

from snownlp import SnowNLP





s = SnowNLP('这款手机真不错,拍照很清晰')


print(s.sentiments)  # 0.97(越接近 1 越正面)





s = SnowNLP('物流太慢了,等了 3 天')


print(s.sentiments)  # 0.05

3. 批量分析 5 万条评论

import pandas as pd


from snownlp import SnowNLP





df = pd.read_csv('comments_50k.csv')





# 打分(5 万条约 2 分钟)


df['score'] = df['text'].apply(lambda t: SnowNLP(str(t)).sentiments)





# 分类:>0.5 正面, <0.4 负面, 中间是中性


def to_label(s):


    if s > 0.5: return 'pos'


    if s < 0.4: return 'neg'


    return 'neu'


df['label'] = df['score'].apply(to_label)





print(df['label'].value_counts())


df.to_csv('sentiment_result.csv', index=False)
实测准确率:电商评论 71%、微博 65%、资讯 78%。通用场景够用,但细分领域(专业、行业)效果差。

4. 进阶:用领域语料重新训练

SnowNLP 自带训练数据是电商语料,在你自家领域可能不准。可以自己训练:

# 准备正负样本(每行一条评论)


# pos.txt: 1000 条正面评论


# neg.txt: 1000 条负面评论





from snownlp import sentiment


sentiment.train('neg.txt', 'pos.txt')


sentiment.save('sentiment.marshal')

训练后,把 sentiment.marshal 替换 SnowNLP 默认模型,准确率通常能提升 10%~15%。

5. 常见坑

想要更高的准确率?下一节的双引擎方案能解决上面所有问题。

嫌 SnowNLP 准确率低?我们的双引擎方案把准确率从 71% 提到 92%

配套软件内置案例数据 + 模板,导入即出图,无需写代码

查看淘宝软件 →