爬取微信好友头像&制作好友头像拼图
import itchat import os import random from PIL import Image import math def headImg(): #获取所有好友的头像,保存在img文件夹中 itchat.login() friends = itchat.get_friends(update=True) # itchat.get_head_img() 获取到头像二进制,并写入文件,保存每张头像 if os.path.exists('img') == False: os.mkdir(img) for count, f in enumerate(friends): # 根据userName获取头像 img = itchat.get_head_img(userName=f["UserName"]) imgFile = open("img/" + str(count) + ".jpg", "wb") imgFile.write(img) imgFile.close() def createImg(): #将img文件夹中的头像拼接成一张图 x = 0 y = 0 imgs = os.listdir("img") random.shuffle(imgs) # 创建640*640的图片用于填充各小图片 newImg = Image.new('RGBA', (640, 640)) # 以640*640来拼接图片,math.sqrt()开平方根计算每张小图片的宽高, width = int(math.sqrt(640 * 640 / len(imgs))) # 每行图片数 numLine = int(640 / width) for i in imgs: img = Image.open("img/" + i) # 缩小图片 img = img.resize((width, width), Image.ANTIALIAS) # 拼接图片,一行排满,换行拼接 newImg.paste(img, (x * width, y * width)) x += 1 if x >= numLine: x = 0 y += 1 newImg.save("all.png") headImg() createImg()
主要用到的方法:
itchat.get_friends()
返回完整的好友列表,每个好友为一个字典, 其中第一项为本人的账号信息,传入update=True
, 将更新好友列表并返回,get_friends(update=True)
itchat.get_head_img(userName="")
根据userName
获取好友头像对头像进行拼接的时候,遍历文件夹的图片,
random.shuffle(imgs)
将图片顺序打乱用640*640的大图来平均分每一张头像,计算出每张正方形小图的长宽,压缩头像,拼接图片,一行排满,换行拼接,好友头像多的话,可以适当增加大图的面积
性别统计图
import itchat import matplotlib.pyplot as plt def getSex(): itchat.login() friends = itchat.get_friends(update=True) sex = dict() i = 0 for f in friends: if f["Sex"] == 1: #男 sex["man"] = sex.get("man", 0) + 1 elif f["Sex"] == 2: #女 sex["women"] = sex.get("women", 0) + 1 else: #未知 sex["unknown"] = sex.get("unknown", 0) + 1 i+=1 print(i) # 柱状图展示 for i, key in enumerate(sex): plt.bar(key, sex[key]) plt.show() getSex()
个性签名统计图&词云图
获取好友信息,
Signature
字段是好友的签名,将个性签名保存到.txt文件,部分签名里有表情之类的会变成emoji 类的词,将这些还有特殊符号的替换掉。import itchat import re from wordcloud import WordCloud,ImageColorGenerator import matplotlib.pyplot as plt def getSignature(): itchat.login() friends = itchat.get_friends(update=True) file = open('sign.txt', 'a', encoding='utf-8') for f in friends: signature = f["Signature"].strip().replace("emoji", "").replace("span", "").replace("class", "") # 正则匹配 rec = re.compile("1f\d+\w*|[<>/=]") signature = rec.sub("", signature) file.write(signature + "\n") # 生成词云图 def create_word_cloud(filename): # 读取文件内容 text = open("{}.txt".format(filename), encoding='utf-8').read() # 注释部分采用结巴分词 # wordlist = jieba.cut(text, cut_all=True) # wl = " ".join(wordlist) # 设置词云 wc = WordCloud( # 设置背景颜色 background_color="white", # 设置最大显示的词云数 max_words=2000, # 这种字体都在电脑字体中,window在C:\Windows\Fonts\下,mac下可选/System/Library/Fonts/PingFang.ttc 字体 font_path='C:\\Windows\\Fonts\\simfang.ttf', height=500, width=500, # 设置字体最大值 max_font_size=60, # 设置有多少种随机生成状态,即有多少种配色方案 random_state=30, ) myword = wc.generate(text) # 生成词云 如果用结巴分词的话,使用wl 取代 text, 生成词云图 # 展示词云图 plt.imshow(myword) plt.axis("off") plt.show() wc.to_file('signature.png') # 把词云保存下 getSignature() create_word_cloud('sign')
参考