Python使用微信itchat接口实现查看自己微信的信息功能详解

yipeiwu_com5年前Python基础

本文实例讲述了Python使用微信itchat接口实现查看自己微信的信息功能。分享给大家供大家参考,具体如下:

itchat是python的一个api,可以访问自己的微信信息,功能还蛮好玩的,可以扒取朋友信息,自动回复短信等等。

package:

itchat1.3.10 + python3.5 + wordcloud1.4.1

登录登出:

itchat.login()
#hotReload设置为True,可以保持一段时间登录
itchat.autologin(hotReload=True)
itchat.logout()

获取朋友数据:

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

搜索某个朋友:

itchat.search_friends(name='name')
itchat.search_friends(wechatAccount='wechatid')

公众号和群聊的获取方式也是类似的:

itchat.get_mps(update=True)[0:]
itchat.search_mps()
itchat.get_chatrooms(update=True)[0:]
itchat.search_chatroom()

发信息:

itchat.send(msg='Received Your Message',toUserName=userName])
#username其实是一个id,nickname是微信名字,remarkname是备注名

自动回复信息:

@itchat.msg_register(itchat.content.TEXT)
def simple_reply(recv_msg):
  msg = recv_msg['Text']
  if msg == 'name':
    itchat.send(msg=u'Received name from',toUserName=recv_msg['FromUserName'])
  elif msg == 'age':
    itchat.send(msg=u'Received age from',toUserName=recv_msg['FromUserName'])
itchat.run()
#register也接受其他参数,比如说isGroupChat=True用来只自动回复群聊信息

register还可以注册其他参数:

MAP 地理位置的分享
CARD 名片信息
SHARING 链接分享
PICTURE 表情或照片
RECORDING 语音
ATTACHMENT 附件
VIDEO 视频
FRIENDS 加好友申请,也就是说发起的一个好友申请其实是一条特殊的信息
SYSTEM 系统消息,比如系统推送消息或者是某个群成员发生变动等等
NOTE 通知文本,比如撤回了消息等等

例子:拉取朋友数据,用wordcloud可视化朋友signature

先读取数据

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

简单分析下性别比例

male = female = other = 0
#friends[0] is personal information, friends start from 1
for i in friends[1:]:
  sex = i["Sex"]
  if sex == 1:
    male += 1
  elif sex == 2:
    female += 1
  else:
    other +=1
total = len(friends[1:])
print("male: %.2f%%" % (float(male)/total*100) + "\n" +
"female: %.2f%%" % (float(female) / total * 100) + "\n" +
"unknown: %.2f%%" % (float(other) / total * 100))

获得各个参数,存入本地

filename = '' #需要修改这里
#爬取各个变量
def get_var(var):
  variable = []
  for i in friends:
    value = i[var]
    variable.append(value)
  return variable
#把数据存到csv文件中,保存到桌面
NickName = get_var("NickName")
Sex = get_var('Sex')
Province = get_var('Province')
City = get_var('City')
Signature = get_var('Signature')
from pandas import DataFrame
data = {'NickName': NickName, 'Sex': Sex, 'Province': Province,
    'City': City, 'Signature': Signature}
frame = DataFrame(data)
frame.to_csv(filename, index=True)

去除特殊字符和转义字符等

import re
siglist = []
for i in friends:
  signature = i["Signature"].strip().replace("span","").replace("class","").replace("emoji","")
  rep = re.compile("1f\d+\w*|[<>/=]")
  signature = rep.sub("", signature)
  siglist.append(signature)

查看signature列表

#去掉末尾的空格以及空的签名
while '' in siglist:
  siglist.remove('')
for i in range(len(siglist)):
  siglist[i].strip()
  print(i,siglist[i])
#wordcloud读取数据要求为string,以空格隔开
text = "".join(siglist)

可视化签名

import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
import PIL.Image as Image
picture_path = '' #这里需要修改
coloring = np.array(Image.open(picture_path))
my_wordcloud = WordCloud(background_color="white", max_words=2000, font_path="2.ttf",
             mask = coloring, max_font_size=60, random_state=42, scale=2).generate(text)
image_colors = ImageColorGenerator(coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()

保存:

save_path = '' #这里需要修改
my_wordcloud.to_file(save_path)

这里是以自己选的picture为形状,生成词云,以下是我的生成结果:

 

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python绘制双柱形图代码实例

python绘制双柱形图代码实例

图表是比干巴巴的表格更直观的表达,简洁、有力。工作中经常遇到的场景是,有一些数值需要定时的监控,比如服务器的连接数、活跃用户数、点击某个按钮的人数,并且通过邮件或者网页展示出来。当我们想...

简单了解Django模板的使用

简单了解Django模板的使用

模板标签include的使用 {%include"police/module/carousel.html"withimgs=imgsdiv_id='#carousel-index'%}...

Python日期操作学习笔记

比如用 print ','.join(datelist) 就可以将datelist列表里面的所有项目并成一个字符串,当然这个表达式会在每一个项目中间插入一个逗号,这种方式比用循环的方式更...

基于Python检测动态物体颜色过程解析

基于Python检测动态物体颜色过程解析

本篇文章将通过图片对比的方法检查视频中的动态物体,并将其中会动的物体定位用cv2矩形框圈出来。本次项目可用于树莓派或者单片机追踪做一些思路参考。寻找动态物体也可以用来监控是否有人进入房间...

Python列表append和+的区别浅析

在python中使用列表的时候大家经常会需要向一个列表中添加一个元素,像下面这两种使用方法需要注意: 复制代码 代码如下: t = [1, 2, 3] t1 = t.append([4]...