Python登录微信分析好友数据

使用环境

本人使用的是jupyter,没有在pycharm中尝试过,有时候可能会出现登录二维码弹不出来的情况,还有就是出来的二维码尺寸过大,无法识别

1、首先,登录微信,执行后悔弹窗出来二维码,扫描登录,如果这时候电脑端登录了会被挤掉

import itchat
import numpy as np
import pandas as pd

itchat.login()

 
 

2、读自己微信好友的数据,也可以将数据输出到csv文件,方便直接看

friends = itchat.get_friends(update=True)
df = pd.DataFrame(friends)
#print(df.head())
df.describe()
df.to_csv('data.csv',index=True,encoding='gb2312')

3、输出的数据一共有33个维度,有的列不知道具体是什么,下面着重看自己知道的几个维度的数据,首先看下自己好友的男女占比

#初始化计数器
male = female = other = 0
#friends[0]是自己的信息,所以要从friends[1]开始
for i in friends[1:]:
    sex = i["Sex"]
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other +=1
#计算朋友总数
total = len(friends[1:])
#格式化输出自己的好友性别比例
print('整体好友:',total)
print('男性好友:',male)
print('女性好友:',female)
print('不明好友:',other)
print("男性好友占比: %.2f%%" % (float(male)/total*100) + "\n" +
"女性好友占比: %.2f%%" % (float(female) / total * 100) + "\n" +
"不明性别好友: %.2f%%" % (float(other) / total * 100))

4、做饼状图看好友占比

#饼状图看下占比关系
#图中中文显示
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

labels = '男','女','不明'
sizes = [174,212,20]

plt.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=False,startangle=90)
plt.title('好友性别分布',fontproperties='SimHei',fontsize=30)
plt.axis('equal')  #这个表示使得饼图圆一点
plt.show()

5、然后看下自己好友的地域分布,这里按照省份和城市聚合

weixin_data = df[['Province','City']]
weixin_data_province = weixin_data.groupby('Province').count()
weixin_data_city = weixin_data.groupby('City').count()

然后同样作图,这里weixin_data_province数据类型为DataFrame,不需要再转np.array

#省份分布
weixin_data_province.plot(kind='bar',figsize=(20,4))

#城市分布
weixin_data_city.plot(kind='bar',figsize=(20,6))

6、然后可以看下好友个性签名的词云

import re
siglist = []
for i in friends:
    signature = i["Signature"].strip().replace("span","").replace("class","").replace("emoji","")
    rep = re.compile("1f\d+\w*|[<>/=]")
    signature = rep.sub("", signature)
    siglist.append(signature)
text = "".join(siglist)
import jieba
wordlist = jieba.cut(text, cut_all=True)
word_space_split = " ".join(wordlist)

import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
import PIL.Image as Image
coloring = np.array(Image.open("timg.jpg"))
my_wordcloud = WordCloud(background_color="white", max_words=100,
                         mask=coloring, max_font_size=80, random_state=42, scale=2,
                         font_path="HYQiHei-25J.ttf").generate(word_space_split)

image_colors = ImageColorGenerator(coloring)
my_wordcloud.to_file("pjl_cloud4.jpg") #保存图片
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()


这样就会输出一个图,但是我这里jupyter里输出的特别不清楚,保存下来打开就清楚,但是是个长方形

这里只选了200个词,好友多的可以多输出点看下



猜你喜欢

转载自blog.csdn.net/huobumingbai1234/article/details/79999786