Python 实现 AI 绘画用户评价自动分类与分析报告生成
将数据科学、人工智能与商业决策结合起来,往往能解决很多实际痛点。下面我将提供一个基于 Python 的完整方案:自动化分析 AI 绘画产品的用户评价,将其分类为'满意'、'一般'或'不满意',并输出包含统计数据和改进建议的报告。
为什么需要这个工具?
想象一下,你负责一个 AI 绘画产品(如 Midjourney, Stable Diffusion 等)。每天 Discord、应用商店评论区涌入大量反馈。想知道用户对某个新功能是否满意?人工阅读成千上万条评论是不现实的。
传统方式面临几个核心问题:
- 信息过载:数据量大,人工效率低且易遗漏。
- 主观偏差:不同人员结论不一,缺乏客观标准。
- 洞察滞后:总结完趋势时,可能已错过最佳调整时机。
- 难以量化:无法精确衡量功能改进后负面评价是否减少。
本项目的核心是一个自动化的评价分析流水线,旨在将主观反馈转化为客观数据。
核心逻辑与流程
整个处理过程分为四个步骤:
- 数据输入:读取文本文件,每行一条评价。
- 文本预处理:清洗数据,转为小写、移除标点,提高分析准确度。
- 情绪分析:调用 NLP 模型(本项目使用 TextBlob)计算极性分数。
- 报告生成:汇总结果,计算占比,提取代表性评论,并基于阈值自动生成改进建议。
代码模块化实现
为了保持清晰,我们将代码拆分为三个主要模块。
1. 配置文件 (config.py)
存放项目设置和分类阈值。
# config.py
FEEDBACK_FILE_PATH = "user_reviews.txt" # 输入的用户评价文件路径
REPORT_OUTPUT_PATH = "review_analysis_report.md" # 生成的报告文件路径
# 定义情绪分类的阈值
SATISFIED_THRESHOLD = 0.3
UNSATISFIED_THRESHOLD = -0.3
2. 评价分析核心模块 (review_analyzer.py)
负责加载数据、预处理及情绪打分。
# review_analyzer.py
import nltk
from textblob import TextBlob
import string
from collections import Counter
from config import FEEDBACK_FILE_PATH, SATISFIED_THRESHOLD, UNSATISFIED_THRESHOLD
# 确保 NLTK 的 punkt 分词器已下载
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
print("[INFO] Downloading required NLTK resource...")
nltk.download('punkt')
class ReviewAnalyzer:
def __init__(self):
pass
def _preprocess_text(self, text):
"""
对文本进行简单的预处理,移除标点符号并转为小写。
"""
translator = str.maketrans('', '', string.punctuation)
text_no_punct = text.translate(translator)
return text_no_punct.lower()
def analyze_single_review(self, review_text):
"""
分析单条评价的情绪。
Returns:
tuple: (sentiment_label, polarity_score)
"""
preprocessed_text = self._preprocess_text(review_text)
blob = TextBlob(preprocessed_text)
polarity = blob.sentiment.polarity
if polarity > SATISFIED_THRESHOLD:
label = 'Satisfied'
elif polarity < UNSATISFIED_THRESHOLD:
label = 'Unsatisfied'
else:
label = 'Neutral'
return label, polarity
def analyze_all_reviews(self):
"""
读取文件中的所有评价并进行分析。
"""
results = []
try:
with open(FEEDBACK_FILE_PATH, 'r', encoding='utf-8') as f:
review_lines = f.readlines()
print(f"[INFO] Loaded {len(review_lines)} review entries.")
for line_num, line in enumerate(review_lines):
review = line.strip()
if not review:
continue
label, score = self.analyze_single_review(review)
results.append({
'original_text': review,
'sentiment_label': label,
'polarity_score': score,
'line_number': line_num + 1
})
return results
except FileNotFoundError:
print(f"[ERROR] Review file not found at '{FEEDBACK_FILE_PATH}'")
return []
3. 报告生成模块 (report_generator.py)
这是产生商业价值的部分,它根据分析结果生成 Markdown 报告。
# report_generator.py
from collections import Counter
from review_analyzer import ReviewAnalyzer
from config import REPORT_OUTPUT_PATH
class ReportGenerator:
def __init__(self):
self.analyzer = ReviewAnalyzer()
def generate_report(self):
"""
生成并保存评价分析报告。
"""
print("\n--- 开始进行评价分析 ---")
analysis_results = self.analyzer.analyze_all_reviews()
if not analysis_results:
print("[FAIL] 没有可分析的数据,报告生成中止。")
return
# 1. 统计情绪分布
labels = [res['sentiment_label'] for res in analysis_results]
label_counts = Counter(labels)
total_reviews = len(analysis_results)
satisfied_percentage = (label_counts.get('Satisfied', 0) / total_reviews) * 100
unsatisfied_percentage = (label_counts.get('Unsatisfied', 0) / total_reviews) * 100
neutral_percentage = (label_counts.get('Neutral', 0) / total_reviews) * 100
# 2. 提取代表性评论
top_satisfied = sorted([res for res in analysis_results if res['sentiment_label'] == 'Satisfied'],
key=lambda x: x['polarity_score'], reverse=True)[:3]
top_unsatisfied = sorted([res for res in analysis_results if res['sentiment_label'] == 'Unsatisfied'],
key=lambda x: x['polarity_score'])[:3]
# 3. 生成改进建议 (核心商业洞察)
suggestions = []
if unsatisfied_percentage > 30:
suggestions.append("- **紧急行动**:负面情绪占比超过 30%,表明产品存在严重的用户体验问题。应立即组织跨部门会议,深入分析负面评论的具体内容,优先解决高频出现的 Bug 和功能缺陷。")
elif unsatisfied_percentage > 15:
suggestions.append("- **重点关注**:负面情绪值得警惕。建议对用户抱怨最多的几个方面进行专项调研,并考虑推出针对性的小版本更新进行修复和优化。")
if satisfied_percentage > 70:
suggestions.append("- **乘胜追击**:正面反馈极高,说明产品核心价值得到广泛认可。可考虑加大市场宣传力度,或在现有好评基础上,挖掘用户喜爱的深层原因,并尝试应用到新功能的开发中。")
if neutral_percentage > 40:
suggestions.append("- **激活沉默用户**:大量中性评价意味着用户对产品印象平平。可以尝试发起社区活动、征集创意、或与活跃用户建立更紧密的联系,引导他们提供更深入的反馈,并提升他们对产品的参与度。")
# 4. 构建 Markdown 报告内容
report_content = f"# AI 绘画产品用户评价分析报告\n\n"
report_content += f"**分析时间**: 自动生成\n"
report_content += f"**数据来源**: `{self.analyzer.FEEDBACK_FILE_PATH}`\n"
report_content += f"**总评价数**: {total_reviews}\n\n"
report_content += "## 1. 情绪分布概览\n\n"
report_content += f"- **满意**: {label_counts.get('Satisfied', 0)} 条 ({satisfied_percentage:.2f}%)\n"
report_content += f"- **不满意**: {label_counts.get('Unsatisfied', 0)} 条 ({unsatisfied_percentage:.2f}%)\n"
report_content += f"- **中性**: {label_counts.get('Neutral', 0)} 条 ({neutral_percentage:.2f}%)\n\n"
report_content += "## 2. 洞察与建议\n\n"
if not suggestions:
report_content += "> 用户反馈整体健康,情绪分布较为均衡,暂无明显问题。\n\n"
else:
for suggestion in suggestions:
report_content += f"> {suggestion}\n"
report_content += "\n"
report_content += "## 3. 代表性评论\n\n"
report_content += "### 👍 Top 满意评论\n\n"
if top_satisfied:
for comment in top_satisfied:
report_content += f"- `{comment['polarity_score']:.2f}` **{comment['original_text']}**\n"
else:
report_content += "无显著满意评论。\n"
report_content += "\n"
report_content += "### 👎 Top 不满意评论\n\n"
if top_unsatisfied:
for comment in top_unsatisfied:
report_content += f"- `{comment['polarity_score']:.2f}` **{comment['original_text']}**\n"
else:
report_content += "无显著不满意评论。\n"
report_content += "\n"
# 5. 保存报告
with open(REPORT_OUTPUT_PATH, 'w', encoding='utf-8') as f:
f.write(report_content)
print(f"[SUCCESS] 报告已成功生成:{REPORT_OUTPUT_PATH}")
print("您可以用任何 Markdown 阅读器或编辑器打开它。")
4. 主程序入口 (main.py)
# main.py
from report_generator import ReportGenerator
def main():
print("="*50)
print(" Welcome to ArtCriticScope - Review Analyzer ")
print("="*50)
analyzer = ReportGenerator()
analyzer.generate_report()
if __name__ == "__main__":
main()
如何使用
- 准备环境:确保已安装 Python 3.x。
- 安装依赖:在项目目录下运行
pip install textblob nltk。 - 准备数据:在根目录创建
user_reviews.txt,逐行写入用户评价。这个模型画的风景太美了,光影处理简直是神来之笔! 生成速度太慢了,而且经常断线,非常失望。 还行吧,能出图,但跟我的描述总感觉差了点意思。 - 运行程序:执行
python main.py。 - 查看报告:打开生成的
review_analysis_report.md文件。
总结
这个项目展示了如何利用现有的 Python 生态系统快速搭建一个功能强大的分析工具。通过 TextBlob 和 NLTK,我们实现了从原始文本到结构化报告的转化。
它不仅是一个技术 Demo,更是一个具有明确市场定位的产品原型。它将主观的、零散的用户评价,转化为了客观的、可量化的统计数据和建议。这使得团队能够基于数据而非猜测来决定产品的下一步方向,极大地提高了决策的准确性和科学性。未来还可以在此基础上接入数据库、开发 Web 界面或引入更高级的深度学习模型(如 BERT),进一步扩展其能力。
希望这个方案能为你处理海量用户反馈提供一点帮助。

