我用 Python 爬取微信好友,最后发现一个大秘密



640?wx_fmt=png&wxfrom=5&wx_lazy=1

前言

你身处的环境是什么样,你就会成为什么样的人。现在人们日常生活基本上离不开微信,但微信不单单是一个即时通讯软件,微信更像是虚拟的现实世界。你所处的朋友圈是怎么样,慢慢你的思想也会变的怎么样。最近在学习 itchat,然后就写了一个爬虫,爬取了我所有的微信好友的数据。并对其中的一些数据进行分析,发现了一些很有趣的事。

Python 微信好友爬虫

此次的爬虫程序用到的库有很多,其中爬取微信数据用到的是 itchat。需要你先去下安装。安装完成以后,你就可以通过 itchat.login() 这个函数登陆你自己的微信。它回弹出一个网页登陆的二维码,你用手机扫描登陆即可。

然后通过 itchat.get_friends() 这个函数就可以获取到自己好友的相关信息,这些信息是一个 json 数据返回。然后我们就可以根据这些返回的信息,进行正则匹配抓取我们想要的信息,在进行分析。

import itchat
itchat.login()
#爬取自己好友相关信息, 返回一个json文件
friends = itchat.get_friends(update=True)[0:]

0?wx_fmt=jpeg

观察返回的数据,很容易就可以根据关键字发现性别是存放在一个字典里面,它的 key 是「Sex」,男性值为 1,女性为 2,其他是不明性别的(就是没有填的)。

在代码里我定义了一个函数 parse_friends() 通过一个 for 循环,把获取到的数据通过 for 循环保存到 text 字典里。然后再通过 draw() 函数画出柱状图。柱状图使用的是 plt 库

def parse_friedns():
   itchat.login()
   text = dict()
   friedns = itchat.get_friends(update=True)[0:]
   print(friedns)
   male = "male"
   female = "female"
   other = "other"
   for i in friedns[1:]:
       sex = i['Sex']
       if sex == 1:
           text[male] = text.get(male, 0) + 1
       elif sex == 2:
           text[female] = text.get(female, 0) + 1
       else:
           text[other] = text.get(other, 0) + 1
   total = len(friedns[1:])
   print("男性好友: %.2f%%" % (float(text[male]) / total * 100) + "\n" +
         "女性好友: %.2f%%" % (float(text[female]) / total * 100) + "\n" +

         "不明性别好友: %.2f%%" % (float(text[other]) / total * 100))
   draw(text)

def draw(datas):
   for key in datas.keys():
       plt.bar(key, datas[key])

   plt.legend()
   plt.xlabel('sex')
   plt.ylabel('rate')
   plt.title("Gender of Alfred's friends")
   plt.show()

最后打印的结果:

640?wx_fmt=png

不得不多说我微信的 1K 多的好友男女比列非常的不协调,男多女少啊。这让我回想起以前高中一个班 50 个人,女生就 7 个,然后我们班的女生从此就有一个女团称呼「七仙女」。

我的微信好友个性签名的词云图

为了进一步分析我的好友大致都有什么特征,我把好友的个性签名一起抓取,分析制作成词云。

个性签名是保存在 Signature 这个 key 中,由于有些签名包含些表情,最初抓取会变成 emoji、span、class 等等这些无关的词。所以需要先替换掉,另外,还有类似 <>/= 之类的符号,也需要写个简单的正则替换掉,再把所有拼起来,得到 text 字串。

   itchat.login()
   siglist = []
   friedns = itchat.get_friends(update=True)[1:]
   for i in friedns:
       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)

得到的数据最后保存到当前目录名为「text.txt」文本中。

   text = "".join(siglist)
   with io.open('text.txt', 'a', encoding='utf-8') as f:
       wordlist = jieba.cut(text, cut_all=True)
       word_space_split = " ".join(wordlist)
       f.write(word_space_split)
       f.close()

分析好友签名的函数我定义成:parse_signature(),完整代码如下:

def parse_signature():
   itchat.login()
   siglist = []
   friedns = itchat.get_friends(update=True)[1:]
   for i in friedns:
       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)
   with io.open('text.txt', 'a', encoding='utf-8') as f:
       wordlist = jieba.cut(text, cut_all=True)
       word_space_split = " ".join(wordlist)
       f.write(word_space_split)
       f.close()

抓取整理了签名的数据,接下来就是制作出词云。这里使用的是 wordCloud 来进行词云的制作。

词云的制作我定义了一个:draw_signature() 函数,完整代码如下

def draw_signature():
   text = open(u'text.txt', encoding='utf-8').read()
   coloring = np.array(Image.open('3.png'))
   my_wordcloud = WordCloud(background_color="white", max_words=2000,
                        mask=coloring, max_font_size=60, random_state=42, scale=2,
                        font_path="DroidSansFallbackFull.ttf").generate(text)
   image_colors = ImageColorGenerator(coloring)
   plt.imshow(my_wordcloud.recolor(color_func=image_colors))
   plt.imshow(my_wordcloud)
   plt.axis("off")
   plt.show()

运行上面的代码后得到了如下的图,由于好友数量比较多,我分别找了两张图制作出图云。


640?wx_fmt=png


640?wx_fmt=png


努力,奋斗,世界,生活,自己。这些词在我们 1K 多人的好友中出现的最多。大家都非常的优秀,都非常的上进。我想这也正是我为什么每天都在努力学习的原因,环境真的非常的影响一个人。


640?wx_fmt=png


我的签名:人生必有痴,而有后成。现在的我痴迷于各种优秀的人,每天都在向他们学习。希望大家一生当中也有痴迷的一面。


完整的代码我已上传到 GitHub 上:


https://github.com/chihaiyishen/Python-Learning/tree/master/python%20%E7%88%AC%E8%99%AB/wechat



∞∞∞



640?wx_fmt=jpeg&wx_lazy=1

IT派 - {技术青年圈} 持续关注互联网、区块链、人工智能领域 640?wx_fmt=jpeg&wx_lazy=1



公众号回复“Python”

邀你加入{ IT派Python技术群 } 


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值