1. 项目概述
这个基于Python+Django的商品评论分析系统,是我在电商数据分析领域深耕多年后开发的一套实用工具。它能够自动化采集、清洗和分析各大电商平台的商品评论数据,为商家和运营人员提供直观的销售反馈和用户意见洞察。
系统采用Django作为后端框架,配合Python强大的数据分析库,实现了从数据采集到可视化呈现的全流程自动化。我在实际电商运营中发现,人工分析海量评论不仅效率低下,而且容易遗漏重要信息。这套系统正是为了解决这个痛点而生,目前已在多个中小型电商项目中得到验证。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 系统架构设计
2.1 技术选型考量
选择Django作为后端框架主要基于三个考虑:
- Django自带的ORM可以大幅简化数据库操作
- 内置的Admin后台非常适合快速搭建管理系统
- 完善的生态系统和丰富的第三方插件
数据分析部分主要依赖以下Python库:
- Pandas:用于数据清洗和预处理
- Jieba:中文分词处理
- SnowNLP:情感分析
- Matplotlib/Seaborn:数据可视化
2.2 数据库设计
系统采用MySQL作为主数据库,主要包含以下核心表:
sql复制CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`price` decimal(10,2) DEFAULT NULL,
`category` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `comment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL,
`content` text NOT NULL,
`rating` tinyint(4) DEFAULT NULL,
`sentiment_score` float DEFAULT NULL,
`create_time` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `product_id` (`product_id`),
CONSTRAINT `comment_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`)
);
3. 核心功能实现
3.1 评论数据采集模块
我开发了通用的爬虫接口,支持对接多个电商平台API。以京东为例的采集函数:
python复制import requests
from bs4 import BeautifulSoup
def fetch_jd_comments(product_id, page=1):
url = f"https://club.jd.com/comment/productPageComments.action?productId={product_id}&score=0&sortType=5&page={page}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
response = requests.get(url, headers=headers)
data = response.json()
comments = []
for comment in data["comments"]:
comments.append({
"content": comment["content"],
"rating": comment["score"],
"create_time": comment["creationTime"]
})
return comments
注意:实际采集时需遵守各平台的robots.txt规则,建议控制请求频率在合理范围内
3.2 情感分析模块
使用SnowNLP进行基础情感分析,并针对电商评论特点做了优化:
python复制from snownlp import SnowNLP
def analyze_sentiment(text):
s = SnowNLP(text)
# 电商评论特有的情感词库增强
if "不错" in text or "很好" in text:
return min(s.sentiments * 1.2, 1.0)
elif "差" in text or "不好" in text:
return s.sentiments * 0.8
return s.sentiments
3.3 关键词提取与词云生成
python复制import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def generate_wordcloud(comments):
text = " ".join(comments)
words = " ".join(jieba.cut(text))
wc = WordCloud(
font_path="SimHei.ttf",
background_color="white",
max_words=100
).generate(words)
plt.imshow(wc)
plt.axis("off")
plt.savefig("wordcloud.png", dpi=300)
4. 系统部署与优化
4.1 Django项目配置要点
在settings.py中需要特别注意以下配置:
python复制# 缓存配置
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake',
}
}
# 静态文件配置
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# 数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'comment_analysis',
'USER': 'your_username',
'PASSWORD': 'your_password',
'HOST': 'localhost',
'PORT': '3306',
}
}
4.2 性能优化技巧
- 使用Django的select_related减少数据库查询:
python复制comments = Comment.objects.select_related('product').all()
- 对高频访问的数据添加缓存:
python复制from django.core.cache import cache
def get_product_stats(product_id):
key = f"product_stats_{product_id}"
stats = cache.get(key)
if not stats:
stats = calculate_stats(product_id)
cache.set(key, stats, timeout=3600) # 缓存1小时
return stats
- 使用Celery异步处理耗时任务:
python复制@app.task
def async_analyze_comments(product_id):
comments = fetch_comments(product_id)
analyze_comments(comments)
5. 常见问题与解决方案
5.1 中文分词不准确问题
电商领域有很多专业词汇,需要在Jieba中添加自定义词典:
python复制jieba.load_userdict("ecommerce_dict.txt")
词典文件示例:
code复制连衣裙 3 n
智能手机 3 n
蓝牙耳机 3 n
5.2 情感分析偏差处理
针对特定场景的优化方案:
- 建立领域情感词典
- 处理否定句式(如"不是很满意")
- 识别程度副词(如"非常满意")
实现示例:
python复制def enhanced_sentiment(text):
negation_words = ["不", "没", "无"]
degree_words = {"非常":1.3, "很":1.2, "比较":0.9, "稍微":0.8}
base_score = SnowNLP(text).sentiments
# 处理否定
for word in negation_words:
if word in text:
base_score = 1 - base_score
# 处理程度词
for word, factor in degree_words.items():
if word in text:
base_score = min(base_score * factor, 1.0)
return base_score
5.3 大数据量处理技巧
当评论数据量很大时(超过10万条),建议:
- 使用Django的Paginator分页处理
- 考虑使用Elasticsearch替代部分数据库查询
- 对分析结果进行预计算和缓存
分页示例:
python复制from django.core.paginator import Paginator
def paginate_comments(request, comments):
paginator = Paginator(comments, 50) # 每页50条
page_number = request.GET.get('page')
return paginator.get_page(page_number)
6. 系统扩展方向
在实际使用中,我发现系统还可以进一步扩展:
- 竞品对比分析:采集竞品评论数据,进行横向比较
- 用户画像构建:结合评论内容分析用户特征
- 异常评论检测:识别刷单、水军等异常评论
- API服务化:将核心功能封装为RESTful API
竞品分析实现思路:
python复制def compare_products(main_product_id, competitor_ids):
main_stats = get_product_stats(main_product_id)
competitor_stats = [get_product_stats(id) for id in competitor_ids]
comparison = {
"rating": {
"main": main_stats["avg_rating"],
"competitors": [s["avg_rating"] for s in competitor_stats]
},
"sentiment": {
"main": main_stats["avg_sentiment"],
"competitors": [s["avg_sentiment"] for s in competitor_stats]
}
}
return comparison
这套系统从开发到优化历时半年多,期间遇到了不少挑战,比如中文分词的准确性问题、情感分析的偏差问题等。通过不断调整算法和添加业务规则,最终达到了可用的准确度。对于想要入门电商数据分析的开发者,建议先从单个平台的数据采集和分析做起,逐步扩展功能。
