本文目录导读:

我来介绍几种Python情感分析的方法,从简单到复杂都有:
使用TextBlob(最简单)
from textblob import TextBlob
def analyze_sentiment_textblob(text):
blob = TextBlob(text)
sentiment = blob.sentiment
# sentiment.polarity: -1.0(负面) 到 1.0(正面)
# sentiment.subjectivity: 0.0(客观) 到 1.0(主观)
if sentiment.polarity > 0:
return "正面"
elif sentiment.polarity < 0:
return "负面"
else:
return "中性"
# 示例
texts = [
"这个产品太棒了,我非常喜欢!",
"服务很糟糕,再也不来了",
"今天天气不错"
]
for text in texts:
result = analyze_sentiment_textblob(text)
print(f"'{text}' -> {result}")
使用VADER(适合社交媒体文本)
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
def analyze_sentiment_vader(text):
analyzer = SentimentIntensityAnalyzer()
scores = analyzer.polarity_scores(text)
# scores包含: neg, neu, pos, compound
# compound: -1(最负面) 到 +1(最正面)
if scores['compound'] >= 0.05:
return "正面", scores
elif scores['compound'] <= -0.05:
return "负面", scores
else:
return "中性", scores
# 示例
text = "这电影真的超级好看,剧情很精彩!"
sentiment, scores = analyze_sentiment_vader(text)
print(f"情感: {sentiment}")
print(f"分数: {scores}")
使用机器学习模型(BERT)
from transformers import pipeline
def analyze_sentiment_bert(text):
# 加载预训练的情感分析模型
sentiment_analyzer = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english"
)
result = sentiment_analyzer(text)[0]
# result格式: {'label': 'POSITIVE', 'score': 0.9998}
return result['label'], result['score']
# 示例
text = "I love this movie! It's amazing!"
label, score = analyze_sentiment_bert(text)
print(f"情感: {label}, 置信度: {score:.4f}")
中文情感分析(使用SnowNLP)
from snownlp import SnowNLP
def analyze_sentiment_chinese(text):
s = SnowNLP(text)
sentiment = s.sentiments # 0(负面) 到 1(正面)
if sentiment > 0.6:
return "正面", sentiment
elif sentiment < 0.4:
return "负面", sentiment
else:
return "中性", sentiment
# 示例
texts = [
"这家餐厅的菜非常好吃,服务也很周到",
"质量太差了,完全不值这个价格",
"今天去了趟超市,买了些日用品"
]
for text in texts:
sentiment, score = analyze_sentiment_chinese(text)
print(f"'{text}' -> {sentiment} (得分: {score:.2f})")
完整的情感分析函数
import re
import jieba
from collections import Counter
class SentimentAnalyzer:
def __init__(self):
# 简单的情感词典
self.positive_words = ['好', '棒', '喜欢', '优秀', '完美', '满意', '开心']
self.negative_words = ['差', '糟糕', '讨厌', '差劲', '失望', '生气', '伤心']
def preprocess(self, text):
# 文本预处理
text = re.sub(r'[^\w\s]', '', text) # 去除标点
words = jieba.cut(text) # 中文分词
return list(words)
def analyze_by_dict(self, text):
"""基于情感词典的分析"""
words = self.preprocess(text)
positive_count = sum(1 for word in words if word in self.positive_words)
negative_count = sum(1 for word in words if word in self.negative_words)
sentiment_score = positive_count - negative_count
if sentiment_score > 0:
return "正面"
elif sentiment_score < 0:
return "负面"
else:
return "中性"
def analyze_mixed(self, text):
"""综合多种方法分析"""
# VADER分析
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
vader = SentimentIntensityAnalyzer()
vader_score = vader.polarity_scores(text)['compound']
# 词典分析
dict_result = self.analyze_by_dict(text)
# 综合判断
if vader_score > 0.3 and dict_result != "负面":
return "正面"
elif vader_score < -0.3 and dict_result != "正面":
return "负面"
else:
return "中性"
# 使用示例
analyzer = SentimentAnalyzer()
test_cases = [
"这个产品真是太棒了,推荐大家购买!",
"垃圾服务,再也不会来了",
"今天天气还行吧"
]
for text in test_cases:
result = analyzer.analyze_mixed(text)
print(f"文本: {text}")
print(f"情感: {result}")
print("-" * 30)
选择建议
| 方法 | 适合场景 | 准确率 | 速度 |
|---|---|---|---|
| TextBlob | 英文简单分析 | 中等 | 快 |
| VADER | 社交媒体、短文本 | 高 | 快 |
| BERT | 复杂语义分析 | 很高 | 慢 |
| SnowNLP | 中文分析 | 中等 | 快 |
| 自定义词典 | 特定领域 | 可调优 | 快 |
实际应用示例
def sentiment_batch_analysis(texts):
"""
批量情感分析
"""
results = []
for text in texts:
# 使用VADER进行快速分析
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
scores = analyzer.polarity_scores(text)
# 分类
if scores['compound'] >= 0.05:
category = "正面"
elif scores['compound'] <= -0.05:
category = "负面"
else:
category = "中性"
results.append({
'text': text,
'sentiment': category,
'scores': scores,
'confidence': max(scores['pos'], scores['neg'], scores['neu'])
})
return results
# 批量处理示例
reviews = [
"服务态度很好,价格也合理",
"产品有质量问题,联系客服没人理",
"一般般吧,没什么特别的感觉"
]
results = sentiment_batch_analysis(reviews)
for r in results:
print(f"评论: {r['text']}")
print(f"情感: {r['sentiment']} (置信度: {r['confidence']:.2%})")
print("---")
优化技巧
- 领域定制:添加行业特定的情感词典
- 否定词处理:如"不好" → "差"
- 程度副词:如"非常喜欢" → 更强正面
- 表情符号:😊 → 积极,😠 → 消极
选择哪种方法取决于你的具体需求、数据量和精度要求,对于生产环境,建议结合多种方法提高准确率。