使用itchat直接获取微信好友信息。
import itchat
itchat.auto_login()
itchat.dump_login_status()
we_friend = itchat.get_friends(update=True)[:]
print(we_friend)
登录之后,输出好友信息。
这里的we_friend是好友的信息的列表,每一个好友字典的 key 如下表
key | 备注 |
UserName | 微信系统内的用户编码标识 |
NickName | 好友昵称 |
Sex | 性别 |
Province | 省份 |
City | 城市 |
HeadImgUrl | 微信系统内的头像URL |
RemarkName | 好友的备注名 |
Signature | 个性签名 |
好友性别 这里顺便提一下:如果sex=1则代表男性,sex=2代表女性
total = len(we_friend[1:])
man = 0
woman = 0
other = 0
for fri_info in we_friend[1:]:
sex = fri_info['Sex']
if sex == 1:
man += 1
elif sex == 2:
woman += 1
else:
other += 1
我这里输出之后:man:155,woman:101,other:13
统计出男生、女生的以及总人数后,占比自然而然就出来了,为了更好的展示男女比例,我们以饼图展示。
绘制饼图
from matplotlib import pyplot as plt
man_ratio = int(man)/total * 100
woman_ratio = int(woman)/total * 100
other_ratio = int(other)/total * 100
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.figure(figsize=(5, 5)) # 绘制的图片为正圆
sex_li = ['男', '女', '其他']
radius = [0.01, 0.01, 0.01]
colors = ['red', 'yellowgreen', 'lightskyblue']
proportion = [man_ratio, woman_ratio, other_ratio]
plt.pie(proportion, explode=radius, labels=sex_li, colors=colors, autopct='%.2f%%') # 绘制饼图
plt.legend(loc="upper right", fontsize=10, bbox_to_anchor=(1.1, 1.1), borderaxespad=0.3)
plt.title('微信好友性别比例')
plt.show()
我的女性好友占比看来还是挺高的。。 占比4.83的是没有设置性别
微信好友地区分布
– 获取区域及城市
prov_dict, city_dict = {}, {}
for fri_info in we_friend[1:]:
prov = fri_info['province']
city = fri_info['city']
if prov and prov not in prov_dict.keys():
prov_dict[prov] = 1
elif prov:
prov_dict[prov] += 1
if city and city not in city_dict.keys():
city_dict[city] = 1
elif city:
city_dict[city] += 1
取好友数量排名前十的城市及区域进行展示
#区域Top10
prov_dict_top10 = sorted(prov_dict.items(), key=lambda x: x[1], reverse=True)[0:10]
#城市Top10
city_dict_top10 = sorted(city_dict.items(), key=lambda y: y[1], reverse=True)[0:10]
prov_nm, prov_num = [], [] # 省会名 + 数量
def city_show(dict_top10):
for prov_data in dict_top10:
prov_nm.append(prov_data[0])
prov_num.append(prov_data[1])
colors = ['#00FFFF', '#7FFFD4', '#F08080', '#90EE90', '#AFEEEE',
'#98FB98', '#B0E0E6', '#00FF7F', '#FFFF00', '#9ACD32']
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
index = range(len(prov_num))
plt.bar(index, prov_num, color=colors, width=0.5, align='center')
plt.xticks(range(len(prov_nm)), prov_nm) # 横坐轴标签
for x, y in enumerate(prov_num):
# 在柱子上方1.2处标注值
plt.text(x, y + 1.2, '%s' % y, ha='center', fontsize=10)
plt.ylabel('省会好友人数') # 设置纵坐标标签
prov_title = '微信好友区域Top10'
plt.title(prov_title) # 设置标题
plt.show()
city_show(prov_dict_top10)
city_show(city_dict_top10)
通过柱形图展示,可以清晰看到好友主要分布