本站内容均来自兴趣收集,如不慎侵害的您的相关权益,请留言告知,我们将尽快删除.谢谢.
随着现代⼈的“⼿机依赖症”越来越深⼊⾻髓,微信⼀定是⼤家每天离不开的⼀款app。通讯,社交,⽀付……
⽽我们的python⼀如既往地强⼤。这篇⽂章就会⼿把⼿地拆解如何利⽤python来爬取微信好友的数据并对它们进⾏分析。
本⽂中使⽤到 的python第三⽅模块主要有:
·itchat 获取微信好友数据
·pyecharts 绘图
·snownlp⽂本情感分析
·jieba 分词
·wordcloud 绘制词云
·百度 ⼈脸 api ⼈脸识别
话不多说,立刻开干!
获取数据
俗话说得好,巧妇难为⽆⽶之炊。因此⾸先我们需要爬取到微信好友的数据,这⾥使⽤到的是 itchat 模块。
itchat 是⼀个开源的微信个⼈号接⼝。安装 itchat ⼗分简单,⽼样⼦,在终端使⽤以下命令即可。
pip install itchat
⽹页爬⾍可能会写长长的代码,然⽽使⽤以下三⾏代码,即可爬取到微信好友数据,so easy。
import itchat itchat.auto_login(hotReload=True) friends =itchat.get_friends(update=True)
通过 itchat.get_friends ⽅法返回来完整的好友列表,其中每个好友为⼀个字典。先来看看它返 回的数据:
这样的数据形式实在是有点辣眼睛,我们再使⽤⼤名⿍⿍的 pandas 将所需要好友信息转化为数据 框的格式存储起来。
长舒⼀⼝⽓,瞬间顺眼了很多。
好友地理位置分析
拿到数据后,我们对微信好友的地理位置进⾏分析。
为了更直观地展⽰数据,我们进⾏了如下的可视化。这⾥我使⽤的是 pyecharts 模块。
pyecharts 的功能强⼤,⽽且作出的图⼗分美观,实在是可视化必备之良品。
from pyecharts import Map provinces_count =data.groupby('province',as_index=True)['province'].coun t().sort_values() attr=list(map(lambda x: x if x !=''else '未知',list(provinces_count.i ndex)))#未填写地址的改为未知 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_t ext_color='#000',visual_range=[0,120]) map_1.render(path='your own path/微信好友分布.html')
颜⾊越趋近于红⾊的地⽅说明好友越多。
可以看到我的好友主要集中在四川,北京,⼴东这三个省 份。
这正是⼩编出⽣,上学,⼯作的⼏个省份,完全契合了我的⽣活轨迹。
再来统计⼀下我的微信好友主要都分布在哪些城市。
from pyecharts import Bar from collections import Counter city_5=Counter(city).most_common(5) bar=Bar('好友所在城市TOP5','',title_pos='center',width=800, height=500)attr,value=bar.cast(city_5) bar.add('',attr,value,is_visualmap=True,visual_text_color='#fff',is_m ore_utils=True,is_label_show=True) bar
emmmm…… 排在第⼀位的是空⽩,也就是说有很多好友并没有标明⾃⼰所在的城市。
当然也许每个⼈的微信⾥都有⼏个位于“安道尔”,“阿布扎⽐”的好友,毕竟城市是⽤户随便填的⽽不是微信定位来的。
排在后⾯的分别为成都,朝阳,海淀,深圳。与上⾯的地图也可以对得上号。
但是微信为何将朝阳和海淀定义为城市⽽不是地区。我不由得陷⼊沉思。
好友性别分析
对好友的性别进⾏分析,来看看我的微信好友男⼥⽐例为多少。同样地这⾥使⽤到了 pyecharts 中的饼图。
from pyecharts import Pie sexs=list(map(lambda x:x['Sex'],friends[1:])) #提取好友性别 value =[sexs.count(1),sexs.count(2),sexs.count(0)]#对性别进⾏计数 sex_attr=['male','female','unknown'] pie=Pie('好友性别⽐例','好友总⼈数:%d'% len(sex),title_pos='center') pie.add('',sex_attr,value,radius=[30,75],rosetype='area',is_label_show=True,is_legend_show=True,legend_top='bottom') pie
如下图所⽰,⼩编的男性好友为51.68%,⼥性好友43.17%,还有少部分没有填写性别的,基本上 算是⼀半⼀半,可以说是⼗分均衡了。
好友签名分析
好友签名是我们获取到的数据中最为丰富的⽂本信息。
毕竟,我们⼤部分⼈都会通过签名来装个⽂艺,提升⼀下逼格,⽐如“缟仙扶醉跨残虹”
或者来个搞笑的,⽐如说“⼤家好,我是性感的贝贝”。
当然也少不了秀恩爱的,⽐如“爱你,只在你在⾝边都是幸福”
对好友签名进⾏分析,这⾥主要使⽤了 jieba , snownlp , wordcloud 等python包。
⾸先,对签名⽂本进⾏清洗,因为签名⽂本中含有emoji表情以及其他⼀些不能识别的字符,因此先 去掉emoji,span等字符。
然后,使⽤ jieba 对个性签名进⾏分词,使⽤ snownlp 进⾏词性的情感 分析。
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) signatures +="".join(jieba.analyse.extract_tags(signature,5))# 关键字提取
然后开始绘制词云
back_coloring=np.array(Image.open("1.jpg"))#图⽚可替换你⾃⼰的图⽚ word_cloud2=WordCloud(font_path ='zt.ttf',background_color ='white',max_words=1200,mask=back_coloring,margin=15) word_cloud2.generate(signatures) image_colors=ImageColorGenerator(back_coloring) plt.figure(figsize=(6,5),dpi=160) plt.imshow(word_cloud2.recolor(color_func=image_colors)) plt.axis("off") plt.show() word_cloud2.to_file("signatures.jpg")
可以看到,词云中⽐较明显的包括“努⼒”,“⼈⽣”,“幸福”等等。
正可谓是物以类聚⼈以群分,正能量的我也拥有正能量的朋友(⼤误)。
再来看看 snownlp 分析好友签名中的情感倾向。代码如下:
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))) value=[count_positive,count_negative,count_neutral] att_attr=['积极','消极','中性'] bar=Bar('个性签名情感分析',title_pos='center',width=800,height=500) bar.add('',att_attr,value,visual_range=[0,200],is_visualmap=True,is_ label_show=True) bar
其中积极和中性的占据了⼤部分,消极的只占据了⼀部分,这个分析结果跟词云给我们的印象也是 吻合的。
好友头像分析
itchat 返回的数据中包括好友头像的url,我们可以通过url将好友头像下载下来,再进⾏分析。
使⽤如下代码可以下载所有的好友头像保存到本地。
basePath=os.path.abspath('.') baseFolder=basePath+'\\HeadImages\\' if(os.path.exists(baseFolder)== False): os.makedirs(baseFolder) image_tags = '' for index in range(1,2): 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)
下载完所有的好友头像后,我们就能够对头像图⽚进⾏分析了。
由于这种图像分析涉及到了⼈脸识别等内容。为了⽅便起见,我们这⾥直接使⽤造好的轮⼦——百度⼈脸识别。
⾸先需要安装百度⼈脸识别sdk,直接输⼊以下命令即可:
pip install baidu-aip
然后,需要在百度应⽤⾥申请开发者账号并创建应⽤,拿到APP_ID, API_KEY以及SECRET_KEY。
接下来就可以在python中调别百度⼈脸识别的服务了。
为了隐私起见,⼩编在这⾥就不⽤微信好友头像来做演⽰了,⽽是使⽤⼀张明星合影来展⽰,原图如下:
百度⼈脸识别服务可以识别出图中的⼈脸,并返回相应的⼈脸信息。代码如下:
from aip import AipFace import base64 APP_ID ="your app_id" API_KEY ="your api_key" SECRET_KEY="your secret_key" client =AipFace(APP_ID,API_KEY,SECRET_KEY)#初始化aipface对象 filepath="your own filepath" with open(filepath,"rb") as fp: base64_data=base64.b64encode(fp.read()) image=str(base64_data,'utf-8') imageType="BASE64" options={} options["face_field"]="age,gender,beauty,expression" options["max_face_num"] =10 options["face_type"]="LIVE" result =client.detect(image,imageType,options)
通过以上代码,我们就能够识别出图⽚中的⼈脸位置,还可以根据 option 选项,可以选择识别返 回⼈脸的年龄,性别,颜值,表情,⼈种等⽅⾯的信息。
我们先来根据返回的⼈脸位置信息,⽤opencv模块作图标识出⼈脸位置:
返回的信息中,即 result 中的信息,⼩编选取了年龄,性别,颜值,和表情这四个维度。
其中, 年龄和颜值都是确定的值,表情和性别均为⼀个值以及对应的概率。
虽然粉丝经常为idol们的颜值⾼低battle到天荒地⽼,也有⼈说“各花⼊各眼”,不过可以看到,在五位⼥明星中,百度⼈脸识别对李冰冰的颜值作出了最⾼评分。
另外expression的判定上,所有⼈的表情均为none,并且概率都为1,果然是时尚杂志都偏爱⾯⽆表情的⾼冷范⼉幺。
最后
⽤python对微信好友进⾏数据分析就告⼀段落。
事实上 itchat 有趣的应⽤还不只这⼀些,还可以利⽤它做聊天机器⼈,⽂件的定时发送等等。
同样的,⽂中所使⽤的其他包都有强⼤应⽤。希望这篇⽂章能给⼤家⼀些⼩⼩的启发,⽐芯〜:heartpulse:
Be First to Comment