思路:
1、通过wxpy获取微信的friends数据
2、通过pymongo存储数据:人员性别数据
3、在pymongo中处理数据:按性别汇总数据
4、利用matplotlib来绘图
5、计划利用djongo来做web来展现数据:简单的点展现性别饼图
第一步:wx.py生成图片保存到本地
from wxpy import *
import pymongo
from pylab import *
mpl.rcParams['font.sans-serif']=['SimHei']
# 上面两行代码解决matplotlib绘图不能显示中文问题
import matplotlib.pyplot as plt
bot=Bot(cache_path ="D:\workplace\Python\Scripts\wxpy.pkl")#连接微信
my_friends=bot.friends() #sex province
# print(my_friends[0].name)
# print(my_friends[0].sex)
print(len(my_friends))
mylist=[]
m=0
for m in range(len(my_friends)):
v_data=[{"name":my_friends[m].name,"sex":my_friends[m].sex}]
mylist=mylist+v_data
m=m+1
#######################################################################################################
#以上获取微信好友数据,并组合成一个集合
#######################################################################################################
myclient=pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient["flydb"]
mycol=mydb["flysite"]
# x=mycol.insert_many(mylist) #会出现反复运行插入操作
print(mycol)
for x in mycol.find():
print(x)
print(mycol.aggregate([{"$group":{"_id":"$sex","personCount":{"$sum":1}}}]))
cursor=mycol.aggregate([{"$group":{"_id":"$sex","personCount":{"$sum":1}}}])
for c in cursor:
v_list=c.values()
v_list=list(v_list)
print(v_list[0])
if list(v_list)[0]==1:
v_men=list(v_list)[1]
elif list(v_list)[0]==2 :
v_women = list(v_list)[1]
elif list(v_list)[0] == 0:
v_other = list(v_list)[1]
print(v_men,v_women,v_other)
#######################################################################################################
##获取汇总数据,类别和值的传入方式需要能适配,目前是固定死的传入方式
#######################################################################################################
labels=['男性','女性','其他']
sizes=[v_men,v_women,v_other]
explode=(0,0.1,0)
fig1,ax1=plt.subplots()
ax1.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',shadow=True,startangle=90)
ax1.axis('equal')
plt.legend()
plt.savefig("D:\\Program Files\\PyCharm 2019.1.1\\untitled1\\static\\sex.png")
###########必须用双杠\\,不然报错,Python中\代表转义
plt.show()
plt.close()
#######################################################################################################
##制作饼图
#######################################################################################################
第二步:django中调用本地图片
views.py
from django.shortcuts import render_to_response
def index(request):
return render_to_response('index.html')
index.html
<h1>微信性别比例</h1>
<img src="/static/sex.png">
urls.py
from laomomo import views #导入views模块
from django.conf.urls import url
urlpatterns=[
url(r'^',views.index),#配置当访问index/时去调用views下的index方法
]
settings.py最后一行增加下述两行,用来默认图片路径,解决图片不现实的问题
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]