前言
因项目需要通过表单提交到数据库然后前端可视化显示。
项目是基于django架构,admin后台美化是用simlpeui。要让django可是数据可视化有两个办法。
第一是echart,但是echart是js,并且后台对接数据麻烦,需要json。大概流程很简单就是给个id,和长宽参数。通过echart.js和echart-wordcloud.js生成,麻烦的是需要js里面的data需要用Ajax获取数据库,其实要是在django后台写入class也可以传递。
第二是用python的模块包但是生成词云也不好,因为都是图片,不能实时读取数据库显示数据库,都是用numpy,pands等模块,有没有其他办法了?有的那就是pyechart(可以理解为用python封装的echart)
思路:
我们通过django的view,操作数据库,连接数据库,读取表,把数据给jieba,jieba分词输出给pyechart的data,pyechart渲染生成html。
django项目
创建django项目,创建app,配置setting,创建models,view以及模板文件。具体看教程
创建完假设我们生成一个表,我们就可以利用jieba和pyechart生成动态词云图
安装模块
安装pyechart,jieba
pip install pyechart
pip install jieba
代码实例
在APP下的view.py中
import pymysql
import jieba
# 连接数据库
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', db='douban', charset='utf8')
cursor = db.cursor()
data = cursor.fetchone()
# 执行查询语句
sql = 'select * from posts'
cursor.execute(sql)
data = cursor.fetchall()
# 开始打印
print("开始打印")
i = 1
str = ""
for res in result:
print(i)
# print(res[5])
str += res[5]
i = i + 1
# print(res)
print(str)
cursor.close()
# 开始用jieba统计词频
words = jieba.lcut(str)
counts = {}
for word in words:
if len(word) == 1: # 排除单个字符的分词结果
continue
else:
counts[word] = counts.get(word, 0) + 1 # 这里的0表示如果word这个键不在字典中,就添加这个键,并且默认为0,如果加上后面的1,就合理了
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) # 以出现的次数为标准,从大到小
for i in range(100):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
运行py文件打印出词和词量
pyechart展示数据
下载pyechart-asstes(离线静态文件,可在gitlab上找)
直接用python打印出来的词频统计,替换实例wordcloud.html中的words