爬了自己的微信,才知道好友都是这样的!
- 2019 年 10 月 4 日
- 筆記
1
写在前面的话
资源君在python的玩耍之路上发现python是越来越有趣,竟然还能去爬取微信上的信息,今天资源君带大家用python来爬一爬自己的微信好友,爬过之后才知道自己的好友是这样的!
环境:python + itchat + matplotlib
2
看看微信好友性别比例
大家知道自己微信里面有多少小哥哥,小姐姐么?今天带大家来看看自己微信到底有多少小哥哥,小姐姐!
- 首先导入我们需要的包:
import itchat import matplotlib.pyplot as plt
2.登录微信
# 登录微信 itchat.login()
3.获取微信好友的性别,并简单计算一下微信好友性别:
# 初始化 man = woman = other = total = 0 # 获取好友 friends = itchat.get_friends(update=True) for item in friends[1:]: if item['Sex'] == 1: man += 1 elif item['Sex'] == 0: woman += 1 else: other += 1 total += 1 # 计算出性别占比 man_all = float(man)/total*100 woman_all = float(woman)/total*100 other_all = float(other)/total*100
4.这一步就是我们把数据进行可视化操作:
# 可视化操作 labels = 'man', 'woman', 'other' fracs = [man_all, woman_all, other_all] explode = [0, 0, 0] plt.axes(aspect=1) plt.pie(x=fracs, labels=labels, explode=explode, autopct='%3.1f %%', shadow=True, labeldistance=1.1, startangle=90, pctdistance=0.6) plt.show()
5.给大家一张效果图(看来资源君微信男性朋友居多):

3
来看看好友来自哪些城市
以为只能看性别吗?当然不是,还可以分析很多东西,再来带大家来看看我们微信好友都来自哪里?(这里只列出排名前三的城市)
- 仍然是导包,这次多了一个pandas,我们这次用柱形图来展示:
import itchat from pandas import DataFrame import matplotlib.pyplot as plt
2. 仍然是登录:
# 登录微信 itchat.login()
3. 处理微信好友的数据,每一行代码的说明我都写在注释里面了:
# 获取朋友列表 friends = itchat.get_friends(update=True) # 利用pandas把数据转化成DataFrame形式 frame = DataFrame(friends) # 获取frame数据中的Province的数据 friends_province = frame.Province city_count = friends_province.value_counts() # 排除没有添加城市的好友 city_count = city_count[city_count.index != ''] # 将数据转化成list格式 city_list = list(city_count.items()) cityname_list = [] citycount_list = [] for item in city_list: cityname_list.append(item[0]) citycount_list.append(item[1])
4. 利用pandas来进行可视化操作,这个地方由于城市过多,我只选取了排名前三的城市来统计:
name_list = ['hunan', 'guangdong', 'beijing'] num_list = citycount_list[0:3] rects = plt.bar(range(len(num_list)), num_list, color='rgby') # X轴标题 index = [0, 1, 2] index = [float(c) + 0.4 for c in index] plt.ylim(ymax=80, ymin=0) plt.xticks(index, name_list) plt.ylabel("number") # X轴标签 for rect in rects: height = rect.get_height() plt.text(rect.get_x() + rect.get_width() / 2, height, str(height)+'%', ha='center', va='bottom') plt.show()
5. 效果如下:

资源君在最后祝大家新年快乐!2019年我们一起变强,变富!