demo.py
from sklearn.cluster import KMeans
import numpy as np
def loadData():
#city.txt 处理成两块=》城市列表,消费数据列表
file=open("city.txt",encoding="utf-8")
cityName=[]
cityDate=[]
for line in file:
# print(line)
items=line.split(",") #items=>["北京","2951.19",......]
cityName.append(items[0])
cityDate.append([ items[i] for i in range(1,len(items)) ])
#实例化means算法类的对象
kmeans=KMeans(n_clusters=5)
#调用 fit_predict()
labels=kmeans.fit_predict(cityDate)
#将城市名称按簇的编号分类
cityCluster=[[],[],[],[],[]]
print(cityName)
print(labels)
for i in range(len(cityName)): #利用cityName的长度产生下标范围
cityCluster[labels[i]].append(cityName[i])
#每个簇中心的平均值进行加和,作为各省市消费水平
expenses=np.sum(kmeans.cluster_centers_,axis=1)
count=[]
for i in range(len(cityCluster)):
print("各消费水平:",expenses[i])
print("各城市名称:",cityCluster[i])
count.append(len(cityCluster[i])) #求每个城市子列表的长度,保存在count中
return expenses,count
if __name__=='__main__':
loadData()
app.py
from flask import Flask,render_template
from demo import loadData
app = Flask(__name__)
@app.route('/')
def hello_word():
expenses,count=loadData()
print(expenses,count)
#series.map(lambda x:处理x)
# map(lambda x:处理x,处理x,序列)
expenses=list(map(lambda x:"%.2f元"%x,expenses)) #map函数返回map对象,将map对象转换成列表
return render_template("index.html",x=expenses,y=count)
if __name__=='__main__':
app.run()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="box" style="width: 550px;height: 400px;margin: 0 auto"></div>
<script src="/static/echarts.min.js"></script>
<script>
var myecharts=echarts,init(document.getElementById("box"),"dark")
var option={
title : {
text: '31省消费水平统计',
},
tooltip : {
trigger: 'axis'
},
legend: {
data:['城市数量']
},
xAxis : [
{
type : 'category',
data : {{ x|safe }}
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'城市数量',
type:'bar',
data:{{ y|safe }}
},
]
};
myecharts.setOption(option)
</script>
</body>
</html>