转自: https://blog.csdn.net/Eastmount/article/details/79618039

最近准备学习微信小程序开发,偶然间看到了python与微信互动的接口itchat,简单学习了下,感觉还挺有意思的,故写了篇基础文章供大家学习。itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机器人。

官网文档:http://itchat.readthedocs.io/zh/latest/

本文主要讲解itchat扩展包的入门基础知识,包括:
1.itchat安装及入门知识
2.微信好友性别分析
3.微信自动回复及发送图片
4.获取微信签名并进行词云分析

基础性文章,希望对您有所帮助,后面将结合舆情分析、朋友圈等接口进行更一步的讲解。如果文章中存在错误或不足之处,还请海涵~

参考文章:
https://zhuanlan.zhihu.com/p/26514576?group_id=839173221667446784
https://www.cnblogs.com/jmmchina/p/6692149.html
http://blog.csdn.net/qinyuanpei/article/details/79360703


 

一. itchat安装及入门知识


安装通过 pip install itchat 命令实现,如下图所示:
 

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析


安装成功之后通过 import itchat 进行导入。

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析


下面给出我们第一个简单的代码:

 
  1. # -*- coding:utf-8 -*-

  2. import itchat

  3.  
  4. # 登录

  5. itchat.login()

  6. # 发送消息

  7. itchat.send(u'你好', 'filehelper')

首先调用itchat.login()函数登录微信,再通过itchat.send(u'你好', 'filehelper')函数发送信息给微信的“文件传输助手(filehelper)”。注意,执行代码过程中会弹出一张二维码图片,我们通过手机扫一扫登录后才能获取我们微信及好友的信息。

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析  [Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析

 

输出结果如下图所示,可以看到给自己发送了一个“你好”。
 

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析


下面给出另一段代码:

 
  1. #-*- coding:utf-8 -*-

  2. import itchat

  3.  
  4. # 先登录

  5. itchat.login()

  6.  
  7. # 获取好友列表

  8. friends = itchat.get_friends(update=True)[0:]

  9. print u"昵称", u"性别", u"省份", u"城市"

  10. for i in friends[0:]:

  11. print i["NickName"], i["Sex"], i["Province"], i["City"]

这里最重要的代码是获取好友列表,代码如下:
    friends = itchat.get_friends(update=True)[0:] 

再通过["NickName"]获取昵称、["Sex"]获取性别、["Province"]获取省份、["City"]获取城市。返回的结果如下所示,其中第一个friends[0]是作者本人,然后性别0表示未填写、1表示男性、2表示女性;省份和城市可以不设置。
 

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析

 

 

二. 微信好友性别分析


下面直接给出对微信好友性别分析绘图的代码:

 
  1. #-*- coding:utf-8 -*-

  2. import itchat

  3.  
  4. #获取好友列表

  5. itchat.login() #登录

  6. friends = itchat.get_friends(update=True)[0:]

  7.  
  8. #初始化计数器

  9. male = 0

  10. female = 0

  11. other = 0

  12.  
  13. #1男性,2女性,3未设定性别

  14. for i in friends[1:]: #列表里第一位是自己,所以从"自己"之后开始计算

  15. sex = i["Sex"]

  16. if sex == 1:

  17. male += 1

  18. elif sex == 2:

  19. female += 1

  20. else:

  21. other += 1

  22. #计算比例

  23. total = len(friends[1:])

  24. print u"男性人数:", male

  25. print u"女性人数:", female

  26. print u"总人数:", total

  27. a = (float(male) / total * 100)

  28. b = (float(female) / total * 100)

  29. c = (float(other) / total * 100)

  30. print u"男性朋友:%.2f%%" % a

  31. print u"女性朋友:%.2f%%" % b

  32. print u"其他朋友:%.2f%%" % c

  33.  
  34. #绘制图形

  35. import matplotlib.pyplot as plt

  36. labels = ['Male','Female','Unkown']

  37. colors = ['red','yellowgreen','lightskyblue']

  38. counts = [a, b, c]

  39. plt.figure(figsize=(8,5), dpi=80)

  40. plt.axes(aspect=1)

  41. plt.pie(counts, #性别统计结果

  42. labels=labels, #性别展示标签

  43. colors=colors, #饼图区域配色

  44. labeldistance = 1.1, #标签距离圆点距离

  45. autopct = '%3.1f%%', #饼图区域文本格式

  46. shadow = False, #饼图是否显示阴影

  47. startangle = 90, #饼图起始角度

  48. pctdistance = 0.6 #饼图区域文本距离圆点距离

  49. )

  50. plt.legend(loc='upper right',)

  51. plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签

  52. plt.title(u'微信好友性别组成')

  53. plt.show()

这段代码获取好友列表后,从第二个好友开始统计性别,即friends[1:],因为第一个是作者本人,然后通过循环计算未设置性别0、男性1和女性2,最后通过Matplotlib库绘制饼状图。如下所示,发现作者男性朋友66.91%,女性朋友26.98%。
 

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析

 

 

三. 微信自动回复及发送图片

 

微信发送信息调用send()函数实现,下面是发送文字信息、文件、图片和视频。

 
  1. # coding-utf-8

  2. import itchat

  3. itchat.login()

  4. itchat.send("Hello World!", 'filehelper')

  5. itchat.send("@[email protected]%s" % 'test.text')

  6. itchat.send("@[email protected]%s" % 'img.jpg', 'filehelper')

  7. itchat.send("@[email protected]%s" % 'test.mkv')

比如给我的微信文件助手发了个“Hello World”和一张图片。

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析


如果想发送信息给指定好友,则核心代码如下:

 
  1. #想给谁发信息,先查找到这个朋友

  2. users = itchat.search_friends(name=u'通讯录备注名')

  3. #找到UserName

  4. userName = users[0]['UserName']

  5. #然后给他发消息

  6. itchat.send('hello',toUserName = userName)


下面这部分代码是自动回复微信信息,同时在文件传输助手也同步发送信息。

 
  1. #coding=utf8

  2. import itchat

  3. import time

  4.  
  5. # 自动回复

  6. # 封装好的装饰器,当接收到的消息是Text,即文字消息

  7. @itchat.msg_register('Text')

  8. def text_reply(msg):

  9. if not msg['FromUserName'] == myUserName: # 当消息不是由自己发出的时候

  10. # 发送一条提示给文件助手

  11. itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" %

  12. (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])),

  13. msg['User']['NickName'],

  14. msg['Text']), 'filehelper')

  15. # 回复给好友

  16. return u'[自动回复]您好,我现在有事不在,一会再和您联系。\n已经收到您的的信息:%s\n' % (msg['Text'])

  17.  
  18. if __name__ == '__main__':

  19. itchat.auto_login()

  20. myUserName = itchat.get_friends(update=True)[0]["UserName"]

  21. itchat.run()

运行结果如下图所示:

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析  [Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析

 

 

四. 获取微信签名并进行词云分析

 

最后给出获取微信好友的签名的词云分析,其friends[i]["Signature"]获取签名,最后调用jieba分词最后进行WordCloud词云分析。

 
  1. # coding:utf-8

  2. import itchat

  3. import re

  4.  
  5. itchat.login()

  6. friends = itchat.get_friends(update=True)[0:]

  7. tList = []

  8. for i in friends:

  9. signature = i["Signature"].replace(" ", "").replace("span", "").replace("class", "").replace("emoji", "")

  10. rep = re.compile("1f\d.+")

  11. signature = rep.sub("", signature)

  12. tList.append(signature)

  13.  
  14. # 拼接字符串

  15. text = "".join(tList)

  16.  
  17. # jieba分词

  18. import jieba

  19. wordlist_jieba = jieba.cut(text, cut_all=True)

  20. wl_space_split = " ".join(wordlist_jieba)

  21.  
  22. # wordcloud词云

  23. import matplotlib.pyplot as plt

  24. from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

  25. import PIL.Image as Image

  26. from scipy.misc import imread

  27. from os import path

  28.  
  29. # 读取mask/color图片

  30. d = path.dirname(__file__)

  31. nana_coloring = imread(path.join(d, "test.png"))

  32.  
  33. # 对分词后的文本生成词云

  34. my_wordcloud = WordCloud(background_color = 'white', # 设置背景颜色

  35. mask = nana_coloring, # 设置背景图片

  36. max_words = 2000, # 设置最大现实的字数

  37. stopwords = STOPWORDS, # 设置停用词

  38. max_font_size = 50, # 设置字体最大值

  39. random_state = 30, # 设置有多少种随机生成状态,即有多少种配色方案

  40. )

  41. # generate word cloud

  42. my_wordcloud.generate(wl_space_split)

  43.  
  44. # create coloring from image

  45. image_colors = ImageColorGenerator(nana_coloring)

  46.  
  47. # recolor wordcloud and show

  48. my_wordcloud.recolor(color_func=image_colors)

  49.  
  50. plt.imshow(my_wordcloud) # 显示词云图

  51. plt.axis("off") # 是否显示x轴、y轴下标

  52. plt.show()

输出结果如下图所示,注意这里作者设置了图片罩,生成的图形和那个类似,发现“个人”、“世界”、“生活”、“梦想”等关键词挺多的。
 

[Python微信开发] 一.itchat入门知识及微信自动回复、微信签名词云分析

 

(By:Eastmount 2018-03-19 晚上11点  http://blog.csdn.net/eastmount/ )

相关文章:

  • 2021-11-30
  • 2022-01-05
  • 2021-05-30
  • 2021-11-26
  • 2021-04-28
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-13
  • 2022-02-08
  • 2022-12-23
  • 2021-12-23
相关资源
相似解决方案