本文实例讲述了Python实现的微信好友数据分析功能。分享给大家供大家参考,具体如下:
这里主要利用python对个人微信好友进行分析并把结果输出到一个html文档当中,主要用到的python包为itchat,pandas,pyecharts等
1、安装itchat 微信的python sdk,用来获取个人好友关系。获取的代码 如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import itchat
import pandas as pd
from pyecharts import Geo, Bar
itchat.login()
friends = itchat.get_friends(update = True )[ 0 :]
def User2dict(User):
User_dict = {}
User_dict[ "NickName" ] = User[ "NickName" ] if User[ "NickName" ] else "NaN"
User_dict[ "City" ] = User[ "City" ] if User[ "City" ] else "NaN"
User_dict[ "Sex" ] = User[ "Sex" ] if User[ "Sex" ] else 0
User_dict[ "Signature" ] = User[ "Signature" ] if User[ "Signature" ] else "NaN"
User_dict[ "Province" ] = User[ "Province" ] if User[ "Province" ] else "NaN"
return User_dict
friends_list = [User2dict(i) for i in friends]
data = pd.DataFrame(friends_list)
data.to_csv( 'wechat_data.csv' , index = True )
|
2、对获取到的数据进行分析。
主要分析了男女比例,以及好友所在城市分布,并且在地图上面展示了微信好友的分布情况。另外其他的数据读者可以自己去分析,这里只是提供一个引导而已。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import pandas as pd
from pyecharts import Geo, Bar
def Cal_mVw(data):
result = {}
for i in data:
if i = = 1 :
result[ "man" ] = result.get( "man" , 0 ) + 1
elif i = = 2 :
result[ "woman" ] = result.get( "woman" , 0 ) + 1
else :
result[ "unknown" ] = result.get( "nunknown" , 0 ) + 1
return result
def count_city(data):
result = {}
for i in data:
if data is not "NaN" or data is not "nan" :
result[i] = result.get(i, 0 ) + 1
return result
data1 = pd.read_csv( 'wechat_data.csv' , encoding = 'GBK' )
manVSwoman = Cal_mVw(data1[ "Sex" ])
#print(manVSwoman)
bar = Bar( "个人微信好友男女比例" )
bar.add( "男女人数" , [ "男" , "女" , "不详" ], [ 139 , 75 , 1 ])
bar.render()
city = count_city(data1[ "City" ])
geo = Geo( "微信好友分布" , " ", title_color=" #fff", title_pos="center",
width = 1200 , height = 600 , background_color = '#404a59' )
#attr, value = geo.cast(city)
geo.add(" ", city.keys(), city.values(), visual_range=[0, 30], visual_text_color=" #fff", symbol_size=15, is_visualmap=True)
geo.show_config()
geo.render()
|
男女比例画出来的图如下所示
获取到的好友分布情况如下图所示:
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/hjxzb/article/details/78347667