参考链接:https://zhuanlan.zhihu.com/p/36418880
一、代码实现:
# -*- coding:utf-8 -*-
# 微信撤回消息
# python2
# 参考链接:https://zhuanlan.zhihu.com/p/36418880
import itchat
itchat.login()
# 爬取自己好友相关信息,返回一个json文件
friends = itchat.get_friends(update=True)[0:]
#print friends
# 1、获得微信好友性别比例
male = female = other = 0
for i in friends[1:]: # friengs[0]是自己的信息
sex = i['Sex']
if sex == 1:
male += 1
elif sex == 2:
female += 1
else:
other += 1
total = len(friends[1:])
print "男性好友: %.2f%%" % (float(male)/total*100) + '\n' + "女性好友: %.2f%%" % (float(female)/total*100) + '\n' +\
"不明性别好友: %.2f%%" % (float(other)/total*100)
# 2、获得微信好友城市分布
# 首先定义一个函数爬去各个变量
def get_var(var):
variable = []
for i in friends:
value = i[var]
if type(value) != int:
value = value.encode('utf-8')
variable.append(value)
return variable
Nickname = get_var('NickName')
#print Nickname
Sex = get_var('Sex')
Province = get_var('Province')
City = get_var('City')
RemarkName = get_var('RemarkName') # 备注名
Signature = get_var('Signature')
from pandas import DataFrame
data = {"NickName":Nickname,"Sex":Sex,"Province":Province,"City":City,"Signature":Signature,"RemarkName":RemarkName}
frame = DataFrame(data)
frame.to_csv('data.csv')
# 3、微信好友签名自定义云图
# 首先将签名表示出来,并去除各种表情什么的,再用正则表达式去除《>=等符号
import re
siglist = []
for i in friends:
signature = i['Signature'].encode('utf-8').strip().replace('span','').replace('class','').replace('emoji',"")
print signature
#siglist.append(signature)
rep = re.compile("1f\d+\w*|[<>/=]") # 正则表达式???没懂。。。
signature = rep.sub('',signature)
siglist.append(signature)
print siglist
text = "".join(siglist)
print text.replace(" ","").replace("\n","")
# 结巴分词包,对字符串进行分词
# 它是Python最好的中文分词组件;
import jieba
wordlist = jieba.cut(text,cut_all=True) # 全模式;False为精确模式;无为默认模式;cut_search_for()为搜索引擎模式
word_space_split = " ".join(wordlist)
print word_space_split
# 画图
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
import numpy as np
import PIL.Image as Image
coloring = np.array(Image.open(r"C:\Users\ZHYU\PycharmProjects\wechat\1.png"))
my_wordcloud = WordCloud(background_color='white',max_words=2000,mask=coloring,max_font_size=60,random_state=42,\
scale=2,font_path=r"C:\Users\ZHYU\Downloads\NotoSans-hinted\NotoSans-Black.ttf").generate(word_space_split)
image_colors = ImageColorGenerator(coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
itchat.logout()
运行结果:
二、遇到的问题
1、编码问题:由于用search_friends()得到的是所有好友信息的json数据,所以得到的昵称、签名等都是u’\u789’这种unicode形式,需要将其转为汉字表示时,用encode(“utf-8”)即可。
2、安装PIL遇到的问题,直接用pip安装后,运行报错:
ImportError: The _imagingft C module is not installed
经过百度找到了解决方案,在此链接上下载与你的系统对应的pillow版本
https://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow即可成功运行!
3、最后的云图出现了乱码……此问题还未解决……下午再看