You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Flask的电商评论情感分析:如何集成Chart.js生成可视化图表

电商评论情感分析可视化集成方案

需求背景

电商店铺需批量分析用户评论的正负情感占比并以图表展示,已完成HTML表单与Flask情感检测功能,需集成Chart.js实现可视化。


第一步:调整Flask后端代码(app.py)

修改predict函数,将计算好的情感占比数值传递给前端,替代仅返回文本描述的逻辑:

import numpy as np
from flask import Flask, request, render_template
from transformers import pipeline
from collections import Counter

sentiment_pipeline = pipeline("sentiment-analysis")
app = Flask(__name__)

@app.route('/')
def home():
    return render_template("Commenting.html")

@app.route('/predict', methods=['POST'])
def predict():
    # 获取表单提交的所有评论
    text = [x for x in request.form.values()]
    status = []
    for sentence in text:
        # 逐个分析情感极性
        status.append(sentiment_pipeline(sentence)[0]['label'])
    
    # 统计正负评论数量(兼容仅单一情感的情况)
    emotion_counter = Counter(status)
    positive_count = emotion_counter.get('POSITIVE', 0)
    negative_count = emotion_counter.get('NEGATIVE', 0)
    total = positive_count + negative_count
    
    # 计算百分比并保留两位小数
    positive_percent = round((positive_count / total) * 100, 2) if total > 0 else 0
    negative_percent = round((negative_count / total) * 100, 2) if total > 0 else 0
    
    # 生成文本描述
    text_sho = f'正面评论占比 {positive_percent}%,负面评论占比 {negative_percent}%'
    
    # 将文本和占比数据传递给前端模板
    return render_template('Commenting.html', 
                           prediction_text=text_sho,
                           positive=positive_percent,
                           negative=negative_percent)

if __name__ == "__main__":
    app.run(debug=True)

第二步:修改HTML页面(Commenting.html)

引入Chart.js库,添加图表容器并编写渲染逻辑:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>商品评论情感分析</title>
    <!-- 引入Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <form action="{{ url_for('predict')}}" method="post">
        <label for="comment1">评价商品1</label><br>
        <input type="text" id="comment1" name="comment1" required="required"><br>
        <label for="comment2">评价商品2</label><br>
        <input type="text" id="comment2" name="comment2" required="required"><br>
        <label for="comment3">评价商品3</label><br>
        <input type="text" id="comment3" name="comment3" required="required"><br>
        <input type="submit" value="提交分析">
    </form>
    
    <h4 style="color:Violet;">{{ prediction_text }}</h4>

    <!-- 仅当后端返回数据时渲染图表 -->
    {% if positive is defined %}
    <div style="width: 400px; height: 400px; margin-top: 20px;">
        <canvas id="sentimentChart"></canvas>
    </div>

    <script>
        // 获取Flask传递的占比数据
        const positivePercent = {{ positive }};
        const negativePercent = {{ negative }};

        // 初始化饼图
        const ctx = document.getElementById('sentimentChart').getContext('2d');
        new Chart(ctx, {
            type: 'pie', // 可替换为'bar'生成柱状图
            data: {
                labels: ['正面评论', '负面评论'],
                datasets: [{
                    label: '情感占比',
                    data: [positivePercent, negativePercent],
                    backgroundColor: ['#4CAF50', '#f44336'],
                    borderColor: '#ffffff',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `${context.label}: ${context.parsed}%`;
                            }
                        }
                    }
                }
            }
        });
    </script>
    {% endif %}
</body>
</html>

核心优化点

  1. 后端容错处理:使用Counter.get()避免仅存在单一情感时的索引错误
  2. 数据传递:将百分比数值直接传递给前端,而非仅文本
  3. 前端条件渲染:通过Jinja2模板判断,仅在有分析结果时展示图表
  4. 图表交互:配置tooltip显示具体百分比,支持响应式布局

内容的提问来源于stack exchange,提问作者AI ML

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:56:13