python+itchat 爬取微信好友信息

项目环境

语言:Python3
编辑器:Pycharm
导包:matplotlib、numpy、wordCloud、PIL、jieba、itchatpython

前言

近朱者赤,近墨者黑。微信已成为咱们生活中必不可少的通信社交工具,朋友圈一个分享咱们生活的平台,接下来先拿个人微信好友开刀,一块儿看看咱们的圈子里都有哪些有趣的事。web

爬取性别

itchat.get_friends() 返回完整的好友列表,每一个好友为一个字典, 其中第一项为本人的帐号信息;传入 update=True, 将更新好友列表并返回。sex=1为男性,sex=2为女性。其余的就是没填性别的。微信

def draw_sex(): itchat.login() text = dict() friends = itchat.get_friends(update=True)[0:] male = "male" female = "female" other = "other" for i in friends[1:]: sex = i['Sex'] if sex == 1: text[male] = text.get(male, 0) + 1 elif sex == 2: text[female] = text.get(female, 0) + 1 else: text[other] = text.get(other, 0) + 1 for key in text.keys(): plt.bar(key, text[key]) plt.xlabel('sex') plt.ylabel('rate') plt.title("Gender histogram") plt.savefig("sex.png") # 保存图片 plt.ion() plt.pause(5) plt.close() # 图片显示5s,以后关闭 def draw_sex(): itchat.login() text = dict() friends = itchat.get_friends(update=True)[0:] male = "male" female = "female" other = "other" for i in friends[1:]: sex = i['Sex'] if sex == 1: text[male] = text.get(male, 0) + 1 elif sex == 2: text[female] = text.get(female, 0) + 1 else: text[other] = text.get(other, 0) + 1 for key in text.keys(): plt.bar(key, text[key]) plt.xlabel('sex') plt.ylabel('rate') plt.title("Gender histogram") plt.savefig("sex.png") # 保存图片 plt.ion() plt.pause(5) plt.close() # 图片显示5s,以后关闭

在代码里经过一个 for 循环,把获取到的数据经过 for 循环保存到 text 字典里。而后再经过 plt 库函数画出性别柱状图。app

生成签名的词云图

1.获取好友签名信息
Signature字段是好友的签名,在这里使用的是结巴分词,将签名尽量的分红更多的词,将其保存到sign.txt文件中,因为有些签名包含一些表情,抓取会变成 emoji、span、class 等等这些无关的词,将这些含有特殊符号的替换掉。dom

def get_signature(): itchat.login() siglist = [] friends = itchat.get_friends(update=True)[1:] 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) text = "".join(siglist) with io.open('sign.txt', 'a', encoding='utf-8') as f: signature_list = jieba.cut(text, cut_all=True)# 全模式,把文本分红尽量多的词 signature_space_split = " ".join(signature_list) f.write(signature_space_split) f.close() def get_signature(): itchat.login() siglist = [] friends = itchat.get_friends(update=True)[1:] 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) text = "".join(siglist) with io.open('sign.txt', 'a', encoding='utf-8') as f: signature_list = jieba.cut(text, cut_all=True)# 全模式,把文本分红尽量多的词 signature_space_split = " ".join(signature_list) f.write(signature_space_split) f.close()

2.绘制词云图
使用wordcloud生成词云图,读取sign.txt中的签名词,选择一张背景图china.jpg,代码以下:编辑器

def draw_word_cloud(): text = open(u'sign.txt', encoding='utf-8').read() coloring = np.array(Image.open('china.jpg')) wordcloud = WordCloud( # 设置背景颜色 background_color="white", # 设置最大显示的词云数 max_words=2000, mask=coloring, # 设置字体最大值 max_font_size=60, # 设置有多少种随机生成状态,即有多少种配色方案 random_state=42, scale=2, # 这种字体都在电脑字体中,window在C:\Windows\Fonts\下, font_path='C:/Windows/Fonts/simkai.ttf').generate(text) image_colors = ImageColorGenerator(coloring) plt.imshow(wordcloud.recolor(color_func=image_colors)) plt.imshow(wordcloud) plt.axis("off") plt.show() wordcloud.to_file('signature.png') # 把词云保存下 def draw_word_cloud(): text = open(u'sign.txt', encoding='utf-8').read() coloring = np.array(Image.open('china.jpg')) wordcloud = WordCloud( # 设置背景颜色 background_color="white", # 设置最大显示的词云数 max_words=2000, mask=coloring, # 设置字体最大值 max_font_size=60, # 设置有多少种随机生成状态,即有多少种配色方案 random_state=42, scale=2, # 这种字体都在电脑字体中,window在C:\Windows\Fonts\下, font_path='C:/Windows/Fonts/simkai.ttf').generate(text) image_colors = ImageColorGenerator(coloring) plt.imshow(wordcloud.recolor(color_func=image_colors)) plt.imshow(wordcloud) plt.axis("off") plt.show() wordcloud.to_file('signature.png') # 把词云保存下

微信好友头像拼接图

1.获取好友图像
获取好友信息,get_head_img拿到每一个好友的头像,在同目录下新建了文件夹img用于保存好友图像,根据下标i命名头像。svg

def get_head_img(): itchat.login() friends = itchat.get_friends(update=True) for i, f in enumerate(friends): # 根据userName获取头像 img = itchat.get_head_img(userName=f["UserName"]) imgFile = open("img/" + str(i) + ".jpg", "wb") imgFile.write(img) imgFile.close() def get_head_img(): itchat.login() friends = itchat.get_friends(update=True) for i, f in enumerate(friends): # 根据userName获取头像 img = itchat.get_head_img(userName=f["UserName"]) imgFile = open("img/" + str(i) + ".jpg", "wb") imgFile.write(img) imgFile.close()

2.好友图像拼接
遍历img文件夹的图片,用640*640的大图来平均分每一张头像,计算出每张正方形小图的长宽,压缩头像,拼接图片,一行排满,换行拼接,具体代码以下:函数

# 头像拼接图 def create_img(): x = 0 y = 0 imgs = os.listdir("img") # random.shuffle(imgs)将图片顺序打乱, random.shuffle(imgs) # 建立640*640的图片用于填充各小图片 total_img = Image.new('RGBA', (640, 640)) # math.sqrt()开平方根计算每张小图片的宽高, width = int(np.math.sqrt(640 * 640 / len(imgs))) # 每行图片数 row_num = int(640 / width) for i in imgs: try: img = Image.open("img/" + i) # 缩小图片 img = img.resize((width, width), Image.ANTIALIAS) # 拼接图片,一行排满,换行拼接 total_img.paste(img, (x * width, y * width)) x += 1 if x >= row_num: x = 0 y += 1 except IOError: print("img/ %s can not open" % (i)) total_img.save("result.png") # 头像拼接图 def create_img(): x = 0 y = 0 imgs = os.listdir("img") # random.shuffle(imgs)将图片顺序打乱, random.shuffle(imgs) # 建立640*640的图片用于填充各小图片 total_img = Image.new('RGBA', (640, 640)) # math.sqrt()开平方根计算每张小图片的宽高, width = int(np.math.sqrt(640 * 640 / len(imgs))) # 每行图片数 row_num = int(640 / width) for i in imgs: try: img = Image.open("img/" + i) # 缩小图片 img = img.resize((width, width), Image.ANTIALIAS) # 拼接图片,一行排满,换行拼接 total_img.paste(img, (x * width, y * width)) x += 1 if x >= row_num: x = 0 y += 1 except IOError: print("img/ %s can not open" % (i)) total_img.save("result.png")

效果图

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
更多内容欢迎你们关注
在这里插入图片描述工具