Python分析微信好友性别比例
- 2019 年 11 月 8 日
- 笔记
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42449444/article/details/84981665
开头第一句 Python??!
我使用的环境如下:①Python版本3.7;②64位Win10系统;③IDE:PyCharm。
需要pip好的Python库有:①itchat;②matplotlib。
思路分析:首先调用itchat库的函数来扫二维码登录微信,并获取好友列表。然后对好友列表进行遍历,用计数器统计好男性、女性和未填写性别的人数,这三者除以总人数就可以得到它们各自所占的比例。最后利用matplotlib库中的pyplot来把统计结果绘制成饼状统计图,感觉pyplot和matlab的绘图功能很像啊。
源代码:
import itchat import matplotlib.pyplot as plt itchat.login() #微信扫QRcode登录 friends = itchat.get_friends(update=True)[0:] #获取好友列表 male = female = other = 0 #初始化计数器 #遍历好友列表,列表里自己是第一位,所以不算在好友内 for i in friends[1:]: sex = i["Sex"] #1表示男性,2表示女性 if sex == 1: male += 1 elif sex == 2: female += 1 else: other += 1 total = len(friends[1:]) #总人数 #打印结果 print("男性好友:%.2f%%"%(float(male/total*100))) print("女性好友:%.2f%%"%(float(female/total*100))) print("未填写性别的好友:%.2f%%"%(float(other/total*100))) #颜色 colors = ['yellowgreen','lightskyblue','lightcoral'] #标签 labels = ['other','male','female'] plt.pie([other,male,female],labels=labels,explode=(0,0,0.1),colors=colors,autopct='%1.1f%%') plt.show() #查看性别比例表 我的explode设置的是女性占比部分突出
饼状统计图:
