作者:杨艳奎_718 | 来源:互联网 | 2023-08-22 20:34
参考链接:https://zhuanlan.zhihu.com/p/36418880
一、代码实现:
import itchat
itchat.login()
friends = itchat.get_friends(update=True)[0:]
male = female = other = 0
for i in friends[1:]: sex = i['Sex']if sex == 1:male += 1elif sex == 2:female += 1else:other += 1total = len(friends[1:])
print "男性好友: %.2f%%" % (float(male)/total*100) + '\n' + "女性好友: %.2f%%" % (float(female)/total*100) + '\n' +\"不明性别好友: %.2f%%" % (float(other)/total*100)
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')
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')
import re
siglist = []
for i in friends:signature &#61; i[&#39;Signature&#39;].encode(&#39;utf-8&#39;).strip().replace(&#39;span&#39;,&#39;&#39;).replace(&#39;class&#39;,&#39;&#39;).replace(&#39;emoji&#39;,"")print signaturerep &#61; re.compile("1f\d&#43;\w*|[<>/&#61;]") signature &#61; rep.sub(&#39;&#39;,signature)siglist.append(signature)print siglist
text &#61; "".join(siglist)
print text.replace(" ","").replace("\n","")
import jieba
wordlist &#61; jieba.cut(text,cut_all&#61;True)
word_space_split &#61; " ".join(wordlist)
print word_space_split
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
import numpy as np
import PIL.Image as Imagecoloring &#61; np.array(Image.open(r"C:\Users\ZHYU\PycharmProjects\wechat\1.png"))
my_wordcloud &#61; WordCloud(background_color&#61;&#39;white&#39;,max_words&#61;2000,mask&#61;coloring,max_font_size&#61;60,random_state&#61;42,\scale&#61;2,font_path&#61;r"C:\Users\ZHYU\Downloads\NotoSans-hinted\NotoSans-Black.ttf").generate(word_space_split)
image_colors &#61; ImageColorGenerator(coloring)
plt.imshow(my_wordcloud.recolor(color_func&#61;image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()itchat.logout()
运行结果&#xff1a;
二、遇到的问题
1、编码问题&#xff1a;由于用search_friends()得到的是所有好友信息的json数据&#xff0c;所以得到的昵称、签名等都是u’\u789’这种unicode形式&#xff0c;需要将其转为汉字表示时&#xff0c;用encode(“utf-8”)即可。
2、安装PIL遇到的问题&#xff0c;直接用pip安装后&#xff0c;运行报错&#xff1a;
ImportError: The _imagingft C module is not installed
经过百度找到了解决方案&#xff0c;在此链接上下载与你的系统对应的pillow版本
https://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow即可成功运行&#xff01;
3、最后的云图出现了乱码……此问题还未解决……下午再看