前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >我用 Python 爬取微信好友,最后发现一个大秘密

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

作者头像
IT派
发布2018-07-30 15:53:32
1K1
发布2018-07-30 15:53:32
举报
文章被收录于专栏:IT派IT派

前言

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

Python 微信好友爬虫

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

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

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

观察返回的数据,很容易就可以根据关键字发现性别是存放在一个字典里面,它的 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()

最后打印的结果:

不得不多说我微信的 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()

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

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

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

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

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-05-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 IT派 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • Python 微信好友爬虫
  • 我的微信好友个性签名的词云图
相关产品与服务
即时通信 IM
即时通信 IM(Instant Messaging)基于腾讯二十余年的 IM 技术积累,支持Android、iOS、Mac、Windows、Web、H5、小程序平台且跨终端互通,低代码 UI 组件助您30分钟集成单聊、群聊、关系链、消息漫游、群组管理、资料管理、直播弹幕和内容审核等能力。适用于直播互动、电商带货、客服咨询、社交沟通、在线课程、企业办公、互动游戏、医疗健康等场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档