經過網查得出,使用json中的dumps方式能夠解決問題。通常在須要輸出得上一步使用,這樣能夠便於其餘錯誤得產生html
import jsonjson
# result = json.dumps(b, encoding='UTF-8', ensure_ascii=False)
# list1 = ["陳","湖北"]
# result = json.dumps(list1, encoding='UTF-8', ensure_ascii=False)
# print resultapp
這裏在初始化列表時有個坑,參考:http://www.07net01.com/2016/03/1344777.htmlhtm
# CityCluster = [[],[],[],[]]
# CityCluster = [[]]*4 #坑 這裏的輸出最終達不到想要的上面的效果,但在輸出空列表是會產生迷糊,ip
#覺得是上面的結果,但輸出非空列表時和上述的效果不同。
CityCluster = [list() for i in xrange (k)] #這樣才正確utf-8
# -*- coding:utf-8 -*-
import numpy as np
from sklearn.cluster import KMeans
import jsonci
def loadData(filePath):
fr = open(filePath,'r+')
lines = fr.readlines()
retData = []
retCityName = []
for line in lines:
items = line.strip().split(",")
retCityName.append(items[0])
retData.append([float(items[i]) for i in range(1,len(items))])
for i in range(1,len(items)):
return retData,retCityName
if __name__=='__main__':
data,cityName = loadData('city.txt')
# cityName = json.dumps(cityName,encoding="GBK",ensure_ascii=False)
# print (cityName)
k = 3
km = KMeans(n_clusters=k)
label = km.fit_predict(data)
expenses = np.sum(km.cluster_centers_,axis=1)
print(expenses)
print label
# CityCluster = [[],[],[],[]]
# CityCluster = [[]]*4 #坑
CityCluster = [list() for i in xrange (k)] #這樣才正確
for i in range(len(cityName)):
CityCluster[label[i]].append(cityName[i])
for i in range(len(CityCluster)):
print("Expenses:%.2f" % expenses[i])
CityCluster[i] = json.dumps(CityCluster[i],encoding="GBK",ensure_ascii=False) #爲了可以順利輸出中文
print(CityCluster[i])it