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

yipeiwu_com7年前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程序设计有所帮助。

相关文章

pandas 实现字典转换成DataFrame的方法

把dictd = {'A':0}转换成DataFrame, 首先,DataFrame的语法格式应为: import pandas as pd df = pd.DataFrame({'...

python求素数示例分享

复制代码 代码如下:# 判断是否是素数def is_sushu(num): res=True for x in range(2,num-1):  ...

详解python破解zip文件密码的方法

详解python破解zip文件密码的方法

1、单线程破解纯数字密码 注意: 不包括数字0开头的密码 import zipfile,time,sys start_time = time.time() def extract()...

Python利用matplotlib做图中图及次坐标轴的实例

Python利用matplotlib做图中图及次坐标轴的实例

图中图 准备数据 import matplotlib.pyplot as plt fig = plt.figure() x = [1, 2, 3, 4, 5, 6, 7] y =...

python中关于for循环的碎碎念

为什么要挑战自己在代码里不写for loop?因为这样可以迫使你去使用比较高级、地道的语法或库。文中以python为例子,讲了不少大家其实在别人的代码里都见过、但自己很少用的语法。 这是...