python获取微信好友地区性别分布以及结果可视化

昨天看微信公众号 Python爱好者社区 的一篇文章关于itchat库的,作者是肖涛(公众号GankSharer),参考文章部分代码自己也实现了这个功能。

目录

一、pyecharts库

二、itchat

三、代码实现

四、结果显示


一、pyecharts库

实现可视化我用的是pyecharts,pyecharts 是一个用于生成 Echarts 图表的类库。Echarts 是百度开源的一个数据可视化 JS 库。用 Echarts 生成的图可视化效果非常棒。详细了解移步pyecharts官网

安装pyecharts

pip install pyecharts

在运行代码的时候可能会报错:

ModuleNotFoundError: No module named 'pyecharts_snapshot'

手动安装一下就好了

pip install pyecharts_snapshot

二、itchat

itchat是一个开源的微信个人号接口,具体了解请移步itchat项目简介

三、代码实现

import itchat
import json
from pyecharts import Geo, Bar, Pie


# 获取微信好友信息
class GetFriends(object):
    def __init__(self):
        self.friends = []  # get_friends()返回一个列表
        self.unknown = 0   # 未知性别的人数
        self.female = 0    # 女性人数
        self.male = 0      # 男性人数

    def login(self):
        itchat.auto_login(hotReload=True)  # 短时间内退出程序不用重新登陆
        self.friends = itchat.get_friends(update=True)

    # 保存到本地
    def save(self):
        with open('friends_info.json', 'w', encoding='utf-8') as f:
            f.write(json.dumps(self.friends, indent=4, ensure_ascii=False))  # indent设置缩进

    # 统计性别数量
    def sex_classify(self):
        for friend in self.friends:
            if friend['Sex'] == 0:
                self.unknown += 1
            elif friend['Sex'] == 1:
                self.female += 1
            else:
                self.male += 1

        labels = ['unknown', 'male', 'female']
        sex_num = [self.unknown, self.female, self.male]
        # 画饼图
        pie = Pie("微信好友性别分布")
        pie.add("", labels, sex_num, is_label_show=True)  # is_label_show是否显示标签
        pie.render("sex_num.html")
        # 画环形图
        pie2 = Pie("微信好友性别分布", title_pos='center')
        pie2.add("", labels, sex_num,
                 radius=[40, 75],  # 环形内外圆的半径
                 is_label_show=True,  # 是否显示标签
                 label_text_color=None,  # 标签颜色
                 legend_orient='vertical',  # 图例垂直
                 legend_pos='left'
                 )
        pie2.render("sex_num2.html")

    # 获取省份信息
    def province_info(self):
        dict_province = dict()
        for friend in self.friends:
            key = friend['Province']
            if key not in dict_province.keys():
                dict_province[key] = 1
            else:
                dict_province[key] += 1
        province_list = []
        num_list = []
        for province, num in dict_province.items():
            if province == "":
                province = "其他地区"
            province_list.append(province)
            num_list.append(num)

        # 画柱状图
        bar = Bar("好友省份分布", "data from WeChat")
        bar.add("人数", province_list, num_list)
        bar.show_config()  # 调试输出js配置信息
        bar.render("province.html")

    # 获取城市信息
    def city_info(self):
        dict_city = dict()
        for friend in self.friends:
            key = friend['City']
            if key not in dict_city.keys():
                dict_city[key] = 1
            else:
                dict_city[key] += 1
        city = []
        # max_num = 0  # 某个城市中最多的人数
        for key, value in dict_city.items():
            # 其他地区
            if len(key) == 0:
                continue
            # 过滤英文等非市级
            if len(key) >= 3:
                continue
            city.append(tuple((key, value)))
            # if value > max_num:
            #     max_num = value

        # 地图标注
        geo = Geo("微信好友城市分布图", "data from WeChat", title_color="#fff", title_pos="center",
                  width=1200, height=600, background_color='#404a59')
        attr, value = geo.cast(city)
        geo.add("", attr, value, visual_range=[0, 50], visual_text_color="#fff", symbol_size=15, is_visualmap=True)
        geo.show_config()
        geo.render("city.html")


if __name__ == '__main__':
    test = GetFriends()
    test.login()
    test.save()
    test.sex_classify()
    test.province_info()
    test.city_info()

四、结果显示

最后输出的是几个html文件,使用浏览器打开查看即可。

发布了30 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_40093242/article/details/88375668
今日推荐