用 Python 分析微信好友性别比例

时间:2022-05-07
本文章向大家介绍用 Python 分析微信好友性别比例,主要内容包括0 前言、1 环境说明、2 相关代码、3 相关说明、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

0 前言

上一次是用 python 实现聊天机器人,其中提及到 itchat 这个包,使用了一下,发现挺好玩的,找了相关的代码看了一下,发现可以用来分析微信好友性别比例,于是就玩起来了。

1 环境说明

Win10 系统下 Python3,编译器是 Pycharm,需要安装 itchat、matplotlib、collections 这3个包。

这里只介绍 Pycharm 安装第三方包的方法。

2 相关代码

2.1 饼图

先是导入包

import itchat
import matplotlib.pyplot as plt
from collections import Counter

接着就是用 itchat 登录微信,获取数据

itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)

然后就是主要的代码

sexs = list(map(lambda x: x['Sex'], friends[1:]))
counts = list(map(lambda x: x[1], Counter(sexs).items()))
labels = ['Unknow','Male',   'Female']
colors = ['red', 'yellowgreen', 'lightskyblue']
plt.figure(figsize=(8, 5), dpi=80)
plt.axes(aspect=1)
plt.pie(counts,  # 性别统计结果
        labels=labels,  # 性别展示标签
        colors=colors,  # 饼图区域配色
        labeldistance=1.1,  # 标签距离圆点距离
        autopct='%3.1f%%',  # 饼图区域文本格式
        shadow=False,  # 饼图是否显示阴影
        startangle=90,  # 饼图起始角度
        pctdistance=0.6  # 饼图区域文本距离圆点距离
)
plt.legend(loc='upper right',)
plt.title('%s的微信好友性别组成' % friends[0]['NickName'])
plt.show()

把代码复制到 pycharm,然后直接鼠标右键,选择 "Run" , 过一会儿,屏幕就会弹出一个二维码,扫描二维码,在手机上确认登录,然后等一会儿就好了。

这个过程中不要在手机上退出登录,也不要在别的地方登录网页版微信,然后就可以看见这样的图了。

2.2 柱状图

一样,先是导入包

import itchat
import matplotlib.pyplot as plt

然后是用 itchat 登录微信

itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)

接下来就是统计好友信息,先把所有性别的个数赋值为0,然后开始一个个计算

male = 0
female = 0
other = 0
# friends[0]是自己的信息,因此我们要从[1:]开始
for i in friends[1:]:
    sex = i['Sex']  # 注意大小写,2 是女性, 1 是男性
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other += 1
total = len(friends[1:])  # 计算好友总数
print('好友总数:', total)
print('男性比例:%2f%%' % (float(male) / total * 100))
print('女性比例:%2f%%' % (float(female) / total * 100))
print('未知性别:%2f%%' % (float(other) / total * 100))

然后我们用 matplotlib 画图, x轴是性别、 y轴是性别、 标题是性别分析。

plt.xlabel("sex")  # x轴是性别
plt.ylabel('number')  # y轴是性别
plt.title('sex analysis')  # 标题是性别分析
arr = ['male'] * male  # 男性
arr1 = ['female']*female  # 女性
arr2 = ['unknow'] * other    # 未知
arr.extend(arr1)
arr.extend(arr2)
plt.hist(arr)
plt.show()

运行代码,扫描二维码,登录网页版微信,等一会就可以看见类似下面的图了。

具体数据如下

柱状图如下

3 相关说明

代码直接复制到 pycharm 里面就可以了,按照顺序来,不要打乱顺序。

itchat 的项目主页:https://github.com/littlecodersh/itchat

itchat 的说明文档:http://itchat.readthedocs.io/zh/latest/

饼图的原文链接:https://qinyuanpei.github.io/posts/2805694118/

柱状图的原文链接:http://blog.csdn.net/Lee20093905/article/details/79052795

题图:Photo by GoaShape on Unsplash