EltonLiang

前言

今天看到一篇好玩的文章,可以实现微信的内容爬取和聊天机器人的制作,所以尝试着实现一遍,本文记录了实现过程和一些探索的内容

来源: 痴海 链接:
https://mp.weixin.qq.com/s/oHc5bXKGMOTnb79XD8lKjQ

itchat安装

对微信的控制可以使用itchat来实现,我们找到itchart的官网下查看相关帮助:http://itchat.readthedocs.io/zh/latest/

我这里使用的是Python2.7,所以直接按照说明pip 安装itchat即可

1.实现给文件助手发消息

安装itchat后,使用如下的代码,即可给文件助手发一条消息,登陆时同样使用扫码登陆

import itchat

itchat.auto_login()

itchat.send(\'Hello, filehelper\', toUserName=\'filehelper\')

自回复消息

按照帮助说明,使用如下的示例代码可以实现消息的自动回复

import itchat

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    return msg.text

itchat.auto_login()
itchat.run()

用老婆大人的号测试了一下,可以实现信息的发送和直接回复

需要注意的是,使用同一个微信给自己发消息不起作用


这里为了方便多次运行,可以设置hotReload=True 变量,从而记录登陆的账号

itchat.auto_login(hotReload=True)

2.微信聊天机器人制作

官网教程还有微信机器人,所以照着教程做了一遍。试用后,发现图灵机器人的智商捉鸡,而且比较凶悍

# -*- coding: utf-8 -*-
import requests
import itchat

KEY = \'71f28bf79c820df10d39b4074345ef8c\'

def get_response(msg):
    # 这里我们就像在“3. 实现最简单的与图灵机器人的交互”中做的一样
    # 构造了要发送给服务器的数据
    apiUrl = \'http://www.tuling123.com/openapi/api\'
    data = {
        \'key\'    : KEY,
        \'info\'   : msg,
        \'userid\' : \'wechat-robot\',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        # 字典的get方法在字典没有\'text\'值的时候会返回None而不会抛出异常
        return r.get(\'text\')
    # 为了防止服务器没有正常响应导致程序异常退出,这里用try-except捕获了异常
    # 如果服务器没能正常交互(返回非json或无法连接),那么就会进入下面的return
    except:
        # 将会返回一个None
        return

# 这里是我们在“1. 实现微信消息的获取”中已经用到过的同样的注册方法
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    # 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复
    defaultReply = \'I received: \' + msg[\'Text\']
    # 如果图灵Key出现问题,那么reply将会是None
    reply = get_response(msg[\'Text\'])
    # a or b的意思是,如果a有内容,那么返回a,否则返回b
    # 有内容一般就是指非空或者非None,你可以用`if a: print(\'True\')`来测试
    return reply or defaultReply

# 为了让实验过程更加方便(修改程序不用多次扫码),我们使用热启动
itchat.auto_login(hotReload=True)
itchat.run()

下面是我的实际测试截图

3.爬取一个好友

机器人是官网的教程,微信文章中使用的是对好友数据分布的统计,所以我先尝试实现爬取一个好友的功能

3.1 获取一个好友信息

# -*- coding: utf-8 -*-
import itchat

itchat.auto_login(hotReload=True)
#爬取自己好友相关信息, 返回一个json文件
friends = itchat.search_friends(name=\'Elton\')
print friends

可以看到拿到的数据是一个List

3.2 打印数据到文件中

通过open函数,可以将获取到的数据写入到txt中去

# -*- coding: utf-8 -*-
import itchat

itchat.auto_login(hotReload=True)
#爬取自己好友相关信息, 返回一个json文件
friends = itchat.search_friends(name=\'Elton\')

f = open("out.txt", "w")
print >> f, friends
f.close()

3.3 安装画图软件

为了把统计出来的柱状图绘制出来,安装matplotlib的库

至此,基本上准备条件已经完成

4. 爬取所有好友数据

爬取好友的功能如下,通过将爬取的数据存储到字典中,对性别做统计处理,可以获取总人数和性别分类的数量

def parse_friedns():
    text = dict()
    friedns = itchat.get_friends(update=True)[0:]
    #(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\'%total)
    print("男性好友: %.2f%%" % (float(text[male]) / total * 100) + "\n" +
          "女性好友: %.2f%%" % (float(text[female]) / total * 100) + "\n" +

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


    draw_plot(text,u\'朋友圈男女比例_\')

使用了plt函数来绘制曲线

# 绘制柱状图
def draw_plot(datas,tag=\'\'):
    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")
    if tag==\'\':
        plt.savefig(OUTPUT+USER_NAME+\'_\'+u\'柱状图.png\')    
    else:
        plt.savefig(OUTPUT+USER_NAME+\'_\'+tag+u\'柱状图.png\')

运行程序,爬取所有的好友数据,发现我好友一共515位,其中男性的好友占据了73%,男女比例差异有点大....

好友个性签名词云

通过使用get_friends可以爬取微信的好朋友数据,存储在\'signature.txt\'文件中

def parse_signature():
    siglist = []
    SIGNATURE_PATH=\'signature.txt\'

    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(SIGNATURE_PATH, \'w\', encoding=\'utf-8\') as f:
        wordlist = jieba.cut(text, cut_all=True)
        word_space_split = " ".join(wordlist)
        f.write(word_space_split)
        f.close()
    draw_wordcloud(SIGNATURE_PATH,tag=u\'朋友圈签名\')

通过对文件的解析,可以将词云绘制出来

#绘制词云
def draw_wordcloud(path,tag=\'\'):
    f = open(path,\'r\').read()
    cut_text="".join(jieba.cut(f))
    coloring = np.array(Image.open(\'.\\Pic\\wechat.jpg\'))
    wordcloud = WordCloud(font_path=\'./font/simhei.ttf\',background_color="white",max_words=2000,mask=coloring, scale=2).generate(cut_text)
    image_colors = ImageColorGenerator(coloring)

    #plt.imshow(wordcloud.recolor(color_func=image_colors))
    plt.imshow(wordcloud)
    plt.axis("off")
    if tag==\'\':
        wordcloud.to_file(OUTPUT+USER_NAME+\'_\'+u\'词云.png\')   
    else:
        wordcloud.to_file(OUTPUT+USER_NAME+\'_\'+tag+u\'词云.png\')   

下图是解析出来的词云,可以看到朋友圈的人大部分还是以自己努力生活为目标~

同理,我也爬取了一下朋友圈的城市分布,发现大部分的人都在北京,还有上过学的哈尔滨,南京的同事~

结论

微信还有很多很好玩的信息可以提取,等下一篇有时间可以继续优化这段代码,github地址如下:

https://github.com/ablo120/PythonLearn.git

附录

import itchat

导入爬取微信记录的包

import re

导入python中的正则表达式(re模块)

import io

导入文件读取的包

import matplotlib.pyplot as plt

导入柱状图绘制的包

import jieba

jieba(结巴)是一个强大的分词库,完美支持中文分词





分类:

技术点:

相关文章:

  • 2021-12-09
  • 2021-12-09
  • 2021-06-03
  • 2021-07-28
  • 2019-03-03
猜你喜欢
  • 2021-11-22
  • 2021-07-09
  • 2021-12-09
  • 2021-10-16
  • 2021-08-23
  • 2021-09-30
相关资源
相似解决方案