爬取微信好友男女比例

环境: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

项目地址为:

github

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 如果可以,真希望我们没有认识过,起码现在不会那么落寞。 今天加班,老板把我捎到徐家汇,看时间已经过八点了,想着不早...
    陌路狂猫阅读 228评论 0 0
  • 配置债券型基金降风险 股票投资的不确定性因素比较多,投资者应考虑将资金转入低风险的债券基金或银行理财产品进行避险。...
    覃若思阅读 265评论 0 0
  • 简书的第一篇文章,记录一下今天上午参加徐珂老师的微信面试感想。 第一,当老师询问为什么想要参加这份工作时,我回答了...
    a582309阅读 491评论 0 0