查阅资料之际偶然发现微信朋友圈数据分析的一些代码,于是就拿来分享给大家啦~
代码来源:https://www.cnblogs.com/taixiang/p/9124822.html
部分代码调试报错,略有修改。
# !/usr/bin/env python3.6
# -*- coding: utf-8 -*-
#__author__: Ed Frey
#date: 2018/9/3
import random
import math
import os
import re
import wordcloud
import itchat
from PIL import Image
import matplotlib.pyplot as plt
def headImg():
itchat.auto_login(hotReload=True) #参数设置为True,短时间内再次登录只须微信确认,不需要扫码。
friends = itchat.get_friends(update=True)#获取好友列表,以字典的形式。
for count, f in enumerate(friends): #count为序号从0开始
img = itchat.get_head_img(userName=f["UserName"])
imgFile = open("img/" + str(count) + ".jpg", "wb")
imgFile.write(img)
imgFile.close()
pass
pass
def createImg():
x = 0
y = 0
imgs = os.listdir("img") #遍历img文件夹下所有文件
random.shuffle(imgs) #随机排列img里的图片
# 创建640*640的图片用于填充各小图片
newImg = Image.new('RGBA', (640, 640))
# 在640*640区域内拼接图片,单个头像面积S*个数len(imgs)=640*640;
width = int(math.sqrt(640 * 640 / len(imgs)))
# 每行图片数
numLine = int(math.sqrt(len(imgs)))
for i in imgs:
try:
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
except Exception as e:
pass
newImg.save("all.png")
def getSex():
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)
sex = dict()
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
# 柱状图展示
for i, key in enumerate(sex):
plt.bar(key, sex[key])
plt.show()
pass
def getSignature():
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)
file = open('sign.txt', 'a', encoding='utf-8')
with open('sign.txt', 'a', encoding='utf-8') as file:
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")
pass
pass
pass
def create_word_cloud(filename):
with open("{}.txt".format(filename), encoding='utf-8') as f:
text = f.read()
wc = wordcloud.WordCloud(
# 设置背景颜色
background_color="white",
# 设置最大显示的词云数
max_words=600,
# 这种字体都在电脑字体中,window在C:\Windows\Fonts\下,mac下可选/System/Library/Fonts/PingFang.ttc 字体
font_path='C:\\Windows\\Fonts\\simfang.ttf',
height=800,
width=800,
# 设置字体最大值
max_font_size=96,
# 设置有多少种随机生成状态,即有多少种配色方案
random_state=30,
)
myword = wc.generate(text) # 生成词云
plt.imshow(myword) # 展示词云图
plt.axis("off")
plt.show()
wc.to_file('signature.png') # 把词云保存下
pass
if __name__ == '__main__':
headImg()
createImg()
getSex()
getSignature()
create_word_cloud('sign')
运行完几个效果图贴出来:
怎么样,还不错吧?