关于 Sentiment Analyzer
Sentiment Analyzer 是用于选择和构建文本情感分析流程的技能,涵盖基础情绪分类、方面级情感和情绪检测。它帮助从业者根据数据与准确性需求,权衡规则、预训练、微调及大模型方案。
主要功能
- 01比较分析方法及其取舍
- 02规划情感分析流程与预处理
- 03按方面分析情感
- 04按时间和群组追踪情感
- 05检测情绪、反讽和比较表达
- 06验证结果并报告不确定性
适用场景
- 01为社交媒体或评论选择分析方法
- 02查找用户对特定产品功能的情感
- 03追踪多篇文档中的观点趋势
- 04通过人工核验检查模糊预测
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ eddiebe147/ claude-settings --skill sentiment-analyzer安装后在 Claude Code 中输入/sentiment-analyzer确认已加载。
详细介绍
情感分析器
情感分析器技能将引导你实现情感分析系统,理解文本中的情绪基调和观点。从简单的正面/负面分类,到细致的基于方面的情感分析和情绪检测,本技能涵盖了情感分析能力的完整范围。
情感分析看似简单,实则复杂。讽刺、上下文、领域特定语言和文化差异,都会给简单方法带来挑战。本技能可帮助你根据准确性要求选择合适的技术,无论是快速的基于规则的系统、微调分类器,还是基于大模型的分析。
无论你分析的是客户评论、社交媒体提及、支持工单还是调查问卷回复,本技能都能确保情感分析准确捕捉用户的真实声音。
核心工作流
工作流 1:选择情感分析方法
- 明确需求:
- 粒度:二分类、三分类还是连续值?
- 方面:整体分析还是基于方面的分析?
- 情绪:情感倾向还是特定情绪?
- 语言:单语还是多语?
- 规模:批量处理还是实时处理?
- 评估选项:
方法 速度 准确度 可定制性 适用场景 基于规则(VADER) 非常快 中等 有限 社交媒体、快速分析 预训练(RoBERTa) 快 良好 可微调 通用文本 微调模型 快 最佳 需要数据 特定领域 大模型(GPT-4、Claude) 慢 出色 基于提示词 细致、复杂的分析 - 根据权衡选择
- 规划实现方案
工作流 2:实现情感分析流水线
- 预处理文本:
def preprocess_for_sentiment(text): # Preserve sentiment-relevant features text = normalize_unicode(text) # Handle social media conventions text = expand_contractions(text) # don't -> do not text = normalize_elongation(text) # loooove -> love text = handle_negation(text) # Mark negation scope # Preserve but normalize emoji/emoticons text = convert_emoji_to_text(text) # :) -> [HAPPY] return text - 分析情感:
class SentimentAnalyzer: def __init__(self, model_type="transformer"): if model_type == "transformer": self.model = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment") elif model_type == "vader": self.model = SentimentIntensityAnalyzer() def analyze(self, text): preprocessed = preprocess_for_sentiment(text) result = self.model(preprocessed) return { "text": text, "sentiment": result["label"], "confidence": result["score"] } - 汇总洞察:
- 整体情感分布
- 情感随时间的变化
- 按细分群体/主题划分的情感
- 验证结果
工作流 3:基于方面的情感分析
- 确定要跟踪的方面:
- 产品特性(价格、质量、服务)
- 体验维度(速度、准确度、友好度)
- 适用于你所在领域的自定义方面
- 从文本中提取方面:
def extract_aspects(text, aspect_list): # Find mentions of known aspects found_aspects = [] for aspect in aspect_list: if aspect.lower() in text.lower(): found_aspects.append(aspect) # Also extract using NER or LLM for unknown aspects extracted = extract_noun_phrases(text) return found_aspects + extracted - 分析各方面的情感:
def aspect_sentiment(text, aspects): results = {} for aspect in aspects: # Extract sentences mentioning aspect relevant = extract_aspect_context(text, aspect) # Analyze sentiment of relevant text if relevant: sentiment = analyze_sentiment(relevant) results[aspect] = sentiment return results - 汇总各文档中的方面情感
快速参考
| 操作 | 命令/触发语 |
|---|---|
| 分析情感 | “分析 [text] 的情感” |
| 选择方法 | “[use case] 的最佳情感分析方法” |
| 基于方面的分析 | “分析 [reviews] 中各特性的情感” |
| 检测情绪 | “检测 [text] 中的情绪” |
| 处理讽刺 | “如何在情感分析中处理讽刺” |
| 汇总结果 | “总结情感趋势” |
最佳实践
-
保留情感信号:不要在预处理中丢弃重要线索
- 保留标点(!!与 .)
- 保留大小写模式
- 保留表情符号/颜文字(转换为文本)
- 明确处理否定表达
-
根据领域选择模型:预训练模型存在领域偏差
- Twitter 模型和产品评论模型的表现有所不同
- 微调模型或选择适合领域的模型
- 部署前使用实际数据进行测试
-
正确处理否定表达:“Not bad”并非负面
- 基于规则的方法:标记否定作用范围
- 神经模型:通常会自动处理
- 明确测试否定表达的情况
-
考虑上下文:情感取决于上下文
- 对平价商品来说,“便宜”是正面评价;对奢侈品来说则是负面评价
- 使用基于方面的分析来捕捉细微差异
- 尽可能纳入周边上下文
-
由人工验证:机器情感判定 ≠ 人类情感判定
- 抽样并人工核验结果
- 计算一致性指标
- 针对不一致之处迭代改进
-
报告不确定性:并非所有文本都有明确情感
- 中性是有效类别
- 应标记低置信度预测
- 考虑对模糊情况不作判定
高级技术
基于大模型的细致情感分析
使用语言模型进行复杂分析:
def llm_sentiment_analysis(text, aspects=None):
prompt = f"""Analyze the sentiment of the following text.
Text: "{text}"
Provide:
1. Overall sentiment (positive/negative/neutral/mixed)
2. Confidence (0-1)
3. Key positive aspects mentioned
4. Key negative aspects mentioned
5. Notable emotional tones (joy, frustration, surprise, etc.)
{"Also rate sentiment specifically for these aspects: " + ", ".join(aspects) if aspects else ""}
Respond in JSON format."""
response = llm.complete(prompt)
return json.loads(response)
情绪检测
超越正面/负面,识别具体情绪:
from transformers import pipeline
# Multi-label emotion classification
emotion_classifier = pipeline(
"text-classification",
model="SamLowe/roberta-base-go_emotions",
top_k=None
)
def detect_emotions(text):
results = emotion_classifier(text)[0]
# Filter to significant emotions
significant = [r for r in results if r["score"] > 0.1]
return sorted(significant, key=lambda x: x["score"], reverse=True)
# Example output:
# [{"label": "admiration", "score": 0.45},
# {"label": "joy", "score": 0.32},
# {"label": "gratitude", "score": 0.28}]
比较情感
检测情感比较:
def comparative_sentiment(text):
"""
Detect: "A is better than B" patterns
"""
prompt = f"""Analyze this text for comparative sentiment.
Text: "{text}"
If the text compares entities, identify:
1. Entity A (the preferred/better one)
2. Entity B (the less preferred/worse one)
3. Dimension of comparison (price, quality, etc.)
4. Strength of preference (slight, moderate, strong)
If no comparison, respond with: {{"comparison": false}}
Respond in JSON."""
return llm.complete(prompt)
时间情感跟踪
分析一段时间内的情感变化:
def sentiment_timeline(documents, time_field, window="day"):
"""
Track sentiment trends over time.
"""
# Analyze each document
results = []
for doc in documents:
sentiment = analyze_sentiment(doc["text"])
results.append({
"timestamp": doc[time_field],
"sentiment": sentiment["score"],
"text": doc["text"]
})
# Aggregate by time window
df = pd.DataFrame(results)
df["window"] = df["timestamp"].dt.floor(window)
trends = df.groupby("window").agg({
"sentiment": ["mean", "std", "count"],
"text": lambda x: list(x)[:3] # Sample texts
})
return trends
讽刺检测
在情感分析前处理讽刺:
def detect_sarcasm(text):
"""
Detect potential sarcasm indicators.
"""
indicators = {
"exaggeration": bool(re.search(r'\b(best|worst|ever|always|never)\b', text.lower())),
"air_quotes": '"' in text,
"ellipsis": "..." in text,
"positive_negative_mix": has_mixed_signals(text),
"hashtags": "#sarcasm" in text.lower() or "#not" in text.lower()
}
# Use model for detection
sarcasm_score = sarcasm_model.predict(text)
return {
"is_sarcastic": sarcasm_score > 0.5,
"confidence": sarcasm_score,
"indicators": indicators
}
def sentiment_with_sarcasm(text):
sarcasm = detect_sarcasm(text)
base_sentiment = analyze_sentiment(text)
if sarcasm["is_sarcastic"] and sarcasm["confidence"] > 0.7:
# Flip sentiment
return flip_sentiment(base_sentiment)
return base_sentiment
应避免的常见陷阱
- 在特定领域文本上使用通用模型
- 预处理时移除了与情感相关的特征(表情符号、标点符号)
- 忽略否定词处理
- 将中性视为缺乏观点,而非明确表达中立
- 未根据人工判断验证模型输出
- 假设数据中不存在讽刺
- 在汇总时过度强调极端情感
- 报告情感时未提供置信度/不确定性
评论
支持 Markdown