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)
#去掉末尾的空格以及空的签名
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为形状,生成词云,以下是我的生成结果: