利用python进行微信好友数据分析

昨天无意中看到一篇文章《基于Python实现的微信好友数据分析》,感觉很有趣,就想自己尝试一下。也不太清楚原作者是谁了,也是公众号转载的,基于原问题进行了代码的优化。

    微信是目前我们用的最多的社交软件,古语云“观其友而知其人”。对微信好友的数据分析也是对自身的一种分析。

一、本文将引用多个第三方模块,引用如下:

import itchat
import numpy as np
import os
from collections import Counter
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']#绘图时可以显示中文
plt.rcParams['axes.unicode_minus']=False#绘图时可以显示中文
import TencentYoutuyun
from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator
from PIL import Image
import time
import re
import snownlp
import jieba
import jieba.analyse
import pandas as pd

本人用的python3,以上模块除了TencentYoutuyun和wordcloud,均可以通过pip install 安装。

(1)TencentYoutuyun安装:点击打开链接

(2)wordcloud安装:

访问https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud下载对应版本的安装包,将下载的安装包保存在工作目录下,直接使用pip install 文件名

二、登录微信,获取好友数据:

if __name__ == "__main__":
    itchat.auto_login(hotReload=True)
    friends = itchat.get_friends(update=True)

三、微信好友数据分析:

1、性别分析

    

def fun_analyse_sex(friends):
    sexs = list(map(lambda x:x['Sex'],friends[1:]))#收集性别数据
    counts = list(map(lambda x:x[1],Counter(sexs).items()))#统计不同性别的数量
    counts = sorted(counts)
    labels = ['保密','男','女']#2:女,1:男,0:保密
    colors = ['red','yellow','blue']
    plt.figure(figsize=(8,5), dpi=80)
    plt.axes(aspect=1)
    plt.pie(counts, #性别统计结果
    labels=labels, #性别展示标签
    colors=colors, #饼图区域配色
    labeldistance = 1.1, #标签距离圆点距离
    autopct = '%3.1f%%', #饼图区域文本格式
    shadow = False, #饼图是否显示阴影
    startangle = 90, #饼图起始角度
    pctdistance = 0.6 #饼图区域文本距离圆点距离
    )
    plt.legend(loc='upper left')#标签位置
    plt.title(u'%s的微信好友性别比例' % friends[0]['NickName'])
    plt.show()

结果如下:


男女比例还是均衡的。

2、头像分析

头像分析有两部分,(1)头像是否是人脸;(2)头像标签的词云

(1)第一部分将会用到腾讯优图提供的人脸识别API,需要自己注册获得appid。详细使用文档:点击打开链接

def fun_analyse_HeadImage(friends):
    basePath = os.path.abspath('.')#程序的存储位置
    baseFolder = basePath + '\\HeadImages\\'#创建存储图片的文件夹的位置
    if(os.path.exists(baseFolder) == False):
        os.makedirs(baseFolder)
    else:
        pass
    use_face = 0#使用人脸
    not_use_face = 0#未使用人脸
    appid = '你的appid'
    secret_id = '你的secret_id'
    secret_key = '你的secret_key'
    end_point = TencentYoutuyun.conf.API_YOUTU_END_POINT
    youtu = TencentYoutuyun.YouTu(appid, secret_id, secret_key,end_point)
    image_tags = ""
    for index in range(1,len(friends)):
        friend = friends[index]
        #保存头像文件
        imgFile = baseFolder + '//Image%s.jpg' %str(index)
        imgData = itchat.get_head_img(userName=friend['UserName'])
        if (os.path.exists(imgFile) == False):
            with open(imgFile,'wb') as file:
                file.write(imgData)
        #检测人脸
        time.sleep(1)
        result = youtu.DetectFace(imgFile)
        if result['face']:
            use_face += 1
        else:
            not_use_face += 1
        #头像分类,做词云
        result2 = youtu.imagetag(imgFile)#调用图像标签接口
        image_tags += (",".join(list(map(lambda x:x['tag_name'],result2['tags'])))+',')#将标签文件连接到一起
    labels = [u'使用人脸头像',u'未使用人脸头像']
    counts = [use_face,not_use_face]
    colors = ['red','blue','yellow']
    plt.figure(figsize=(8,5), dpi=120)
    plt.axes(aspect=1)#此处的aspect=1表示正圆,取不同的值,表示的圆形状不同
    plt.pie(counts,#计数
            labels=labels,
            colors = colors,
            labeldistance = 1.1,#标签距离圆心的距离
            autopct = '%3.1f%%', #饼图区域文本格式
            shadow = False,#饼图是否有阴影
            startangle = 90,
            pctdistance = 0.6)
    plt.legend(loc = 'upper right')
    plt.title(u'%s的微信好友使用人脸头像的情况' %friends[0]['NickName'])
    plt.show()
    #绘制头像标签词云
    image_tags = image_tags.encode('iso8859-1').decode('utf-8')#加密解密
    plt.figure(figsize=(8,5), dpi=160)
    back_coloring = np.array(Image.open('face.jpg'))
    word_cloud = WordCloud(font_path = 'simkai.ttf',
                         background_color = 'white',
                         max_words = 1200,
                         mask = back_coloring,
                         max_font_size = 75,
                         stopwords = STOPWORDS.add('写真照'),#ps:这个词有点太露骨了。
                         random_state=45,
                         width=600,
                         height = 300,
                         margin = 15)
    word_cloud.generate(image_tags)
    plt.imshow(word_cloud)
    plt.axis("off")
    plt.show()

结果如下:


大部分人还是没有使用人脸头像的。


女孩这个词十分显眼,推断是女生更喜欢是用个人头像或女星为头像。词云选择的乔布斯为底图背景。

3、签名分析:

好友签名分析,也分为两部分:(1)切词构造词云;(2)文本分析,生活态度

代码如下:

def fun_analyse_Signature(friends):
    signatures = ''
    emotions = []
    for friend in friends:
        signature = friend['Signature']
        if signature != None:
            signature = signature.strip().replace("span","").replace("class","").replace("emoji","")#去除无关数据
            signature = re.sub(r'1f(\d.+)',"",signature)
        if len(signature) > 0:
            nlp = snownlp.SnowNLP(signature)
            emotions.append(nlp.sentiments)#nlp.sentiments:权值
            signatures += " ".join(jieba.analyse.extract_tags(signature,5))#关键字提取
    back_coloring = np.array(Image.open("xiaohuangren.jpg"))#图片可替换
    word_cloud2 = WordCloud(font_path = 'simkai.ttf',
                         background_color = 'white',
                         max_words = 1200,
                         mask = back_coloring,
                         margin = 15)
    word_cloud2.generate(signatures)
    image_colors = ImageColorGenerator(back_coloring)
    plt.figure(figsize=(8,5),dpi=160)
    plt.imshow(word_cloud2.recolor(color_func=image_colors))
    plt.axis("off")
    plt.show()
    word_cloud2.to_file("signatures.jpg")
#人生观
    count_positive = len(list(filter(lambda x:x>0.66,emotions)))#大于0.66为积极
    count_negative = len(list(filter(lambda x:x<0.33,emotions)))#小于0.33为消极
    count_neutral = len(list(filter(lambda x:x>=0.33 and x <= 0.66,emotions)))
    labels = [u'积极',u'中性',u'消极']
    values =(count_positive,count_neutral,count_negative)
    plt.rcParams['font.sans-serif'] = ['simHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.xlabel("情感判断")
    plt.ylabel("频数")
    plt.xticks(range(3),labels)
    plt.legend(loc='upper right')
    plt.bar(range(3),values,color='rgb')
    plt.title(u'%s的微信好友签名信息情感分析情况' % friends[0]['NickName'])
    plt.show()

结果如下:



看来好友还都是蛮积极乐观的。

4、好友位置分析:

今天弄懂了pyecharts,就想起来可以用来做位置分析。

再分析之前,还要安装pychart库,直接pip。

pip install pyecharts
不懂得地方参考本篇文章: http://blog.csdn.net/xxzj_zz2017/article/details/79601135

假设已经配置好环境,接下来进行分析,代码如下:

from pyecharts import Map
def get_attr(friends, key):
    return list(map(lambda user: user.get(key), friends))
def fun_pos(friends)
    users = dict(province=get_attr(friends, "Province"),
                 city=get_attr(friends, "City"),
                 nickname=get_attr(friends, "NickName"))
    provinces = pd.DataFrame(users)
    provinces_count = provinces.groupby('province', as_index=True)['province'].count().sort_values()
    attr = list(map(lambda x: x if x != '' else '未知', list(provinces_count.index)))#未填写地址的改为未知
    value = list(provinces_count)
    map_1 = Map("微信好友位置分布图",title_pos="center",width=1000, height=500)
    map_1.add('', attr, value, is_label_show=True, is_visualmap=True, visual_text_color='#000',visual_range=[0,120])
    map_1

看来还是在北京的朋友多。

暂时只对好友进行了以上几方面的分析,感觉还是很有意思的。



  • 8
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值