环境:win10+python3.6
1.python抓取微信好友数量及好友比例
使用itchat库对微信进行操作
登录微信,跳出一个二维码,扫描即可登录成功
itchat.login()
但是存在的问题就是:每次运行都需要扫码登录,故可以使用另一个方法
itchat.auto_login(hotReload=True)
除第一次登陆需要扫码外,后面只需要在手机确定登陆就行
获取自己好友的相关信息,得到一个json数据返回
data=itchat.get_friends(update=True)
打印之后,发现有很多数据信息,如备注,昵称,城市信息,签名等。
通过sex键得到好友男女数量及比例
itchat.login()
text = dict()
numbers=itchat.get_friends(update=True)
print(len(numbers))
friedns = itchat.get_friends(update=True)[0:]
print(numbers)
print(friedns)
male = "male"
female = "female"
other = "other"
for i in friedns[1:]:
sex = i['Sex']
if sex == 1:
text[male] = text.get(male, 0) + 1
elif sex == 2:
text[female] = text.get(female, 0) + 1
else:
text[other] = text.get(other, 0) + 1
total = len(friedns[1:])
print('男性好友数量:',text[male])
print('女性好友数量:',text[female])
print('未知性别好友数量:',text[other])
print("男性好友比例: %.2f%%" % (float(text[male]) / total * 100) + "\n" +
"女性好友比例: %.2f%%" % (float(text[female]) / total * 100) + "\n" +
"不明性别好友比例: %.2f%%" % (float(text[other]) / total * 100))
最后得到自己好友情况如下
image.png使用matplotlib库来实现微信好友男女比例柱状图显示
from matplotlib import pyplot as plt
def draw(datas):
for key in datas.keys():
plt.bar(key, datas[key])
plt.legend()
plt.xlabel('sex')
plt.ylabel('rate')
plt.title("Gender of Alfred's friends")
图形显示如下
image.png这里柱状图显示却没有显示具体数值,查阅之后发现可以使用plt.text()来实现在柱状图的上方显示数值。
具体的代码修改如下
def draw(datas):
b=[]
for key in datas.keys():
plt.bar(key, datas[key])# 柱状图
b.append(datas[key])
a = datas.keys()
# 使用plt.text()来实现柱状图显示数值
for x, y in zip(a, b):
plt.text(x, y, str(y), ha='center', va='bottom', fontsize=11)
plt.legend()
plt.xlabel('sex')
plt.ylabel('rate')
plt.title("Gender of Alfred's friends")
plt.show()
修改后的图形显示
image.png项目地址为:
网友评论