Python flask + Mysql +Echarts 绘制词云图(笔记)

您所在的位置:网站首页 echarts制作词云图 Python flask + Mysql +Echarts 绘制词云图(笔记)

Python flask + Mysql +Echarts 绘制词云图(笔记)

2024-07-09 23:03| 来源: 网络整理| 查看: 265

目录

步骤一:建立Myslq数据库连接

 步骤二:开发Flask应用

步骤三:创建前端页面(ciyun.html )

 步骤四:运行Flask应用并查看词云图

步骤一:建立Myslq数据库连接 import json import pymysql class Mysql(object): # 创建 Mysql 类的实例时自动调用 def __init__(self): # 建立MySQL数据库连接 self.conn = pymysql.connect(host='localhost', user='root', password='1234', database='Design', charset="utf8") # 创建了一个游标对象cursor,用于执行SQL命令 self.cursor = self.conn.cursor() # 这个方法使得 Mysql 类的实例可以作为上下文管理器使用 def __enter__(self): return self # 负责关闭游标和数据库连接 def __exit__(self, exc_type, exc_val, exc_tb): self.cursor.close() self.conn.close() # 返回的结果是一个元组列表,每个元组代表NameWordCount表中的一行数据。 def get_word_count(self): sql = 'select word,count from NameWordCount order by count desc limit 400;' self.cursor.execute(sql) return self.cursor.fetchall()  步骤二:开发Flask应用

这段代码是一个使用Flask框架编写的简单Web应用程序。这个Web应用程序提供了一个界面来展示词云,并且通过POST请求返回了词频统计的JSON数据,这些数据是用于生成词云的。

from flask import Flask, send_from_directory, jsonify from flask import render_template from mysql import Mysql app = Flask(__name__) @app.route('/ciyun') def getdata(): # 使用 render_template 函数渲染 ciyun.html 模板 return render_template('ciyun.html') @app.route('/data', methods=['POST']) def myciyun(): # 创建了一个 Mysql 类的实例,用于与MySQL数据库建立连接。 db = Mysql() # 调用 db.house() 方法,执行SQL查询并获取结果。 item = db.get_word_count() word = [] count = [] for data in item: word.append(data[0]) count.append(data[1]) return jsonify(word=word, count=count) if __name__ == '__main__': app.run(debug=True) #debug=True发生错误时会返回发生错误的地方 步骤三:创建前端页面(ciyun.html ) 数据可视化 var myChart = echarts.init(document.getElementById('main')); var app={ word1:[], count1:[] }; $(document).ready(function () { getData(); }); function getData() { $.ajax({ url: '/data', data: {}, type: 'POST', async: false, dataType: 'json', success: function (data) { app.word1 = data.word; app.count1 = data.count; } }); } getData(); var word=[]; for(var i = 0;i maskImage: maskImage, sizeRange: [10, 70], width:750, height:800, textStyle: { fontFamily: 'sans-serif', fontWeight: 'bold', color: function () { // Random color return 'rgb(' + [ Math.round(Math.random() * 160), Math.round(Math.random() * 160), Math.round(Math.random() * 160) ].join(',') + ')'; } }, emphasis: { focus: 'self', textStyle: { textShadowBlur: 10, textShadowColor: '#333' } }, data: word }] }; myChart.setOption(option); //随着屏幕大小调节图表 window.addEventListener("resize", () = { myChart.resize(); });  步骤四:运行Flask应用并查看词云图



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3