首先需要安装itchat包,很简单,pip就可以:
pip install itchat
代码1
# -*- coding:utf-8 -*-
import itchat
from pandas import DataFrame
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 += 1
elif sex == 2:
female += 1
else:
other += 1
total = len(friends[1:])
malecol = round(float(male) / total * 100, 2)
femalecol = round(float(female) / total * 100, 2)
othercol = round(float(other) / total * 100, 2)
print('男性朋友:%.2f%%' % (malecol) +
'\n' + '女性朋友:%.2f%%' % (femalecol) +
'\n' + '性别不明的好友:%.2f%%' % (othercol))
# 使用echarts,加上这段
from echarts import Echart, Legend, Pie #pip install echarts-python
chart = Echart(u'%s的微信好友性别比例' % (friends[0]['NickName']), 'from WeChat')
chart.use(Pie('WeChat',
[{'value': male, 'name': u'男性 %.2f%%' % malecol},
{'value': female, 'name': u'女性 %.2f%%' % femalecol},
{'value': other, 'name': u'其他 %.2f%%' % othercol}],
radius=["50%", "70%"]))
chart.use(Legend(["male", "female", "other"]))
del chart.json["xAxis"]
del chart.json["yAxis"]
chart.plot()
def get_var(var):
variable = []
for i in friends:
value = i[var]
variable.append(value)
return variable
NickName = get_var('NickName')#昵称
Sex = get_var('Sex')#性别
Province = get_var('Province')#省份
City = get_var('City')#城市
Signature = get_var('Signature')#签名
data = {'NickName': NickName,
'Sex': Sex,
'Province': Province,
'City': City,
'Signature': Signature
}
frame = DataFrame(data)
frame.to_csv('data.csv', index=True, encoding="utf_8_sig")
好像不够直观,有兴趣的朋友可以加上可视化的展示,我这里用基于python的Echarts 先安装了
pip install echarts-python
展示比例一般使用百分比圆饼表吧
# 使用echarts,加上这段
from echarts import Echart, Legend, Pie
chart = Echart(u'%s的微信好友性别比例' % (friends[0]['NickName']), 'from WeChat')
chart.use(Pie('WeChat',
[{'value': male, 'name': u'男性 %.2f%%' % (float(male) / total * 100)},
{'value': female, 'name': u'女性 %.2f%%' % (float(female) / total * 100)},
{'value': other, 'name': u'其他 %.2f%%' % (float(other) / total * 100)}],
radius=["50%", "70%"]))
chart.use(Legend(["male", "female", "other"]))
del chart.json["xAxis"]
del chart.json["yAxis"]
chart.plot()
代码2
# -*- coding:utf-8 -*-
import itchat
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
#此时稍微等一会,会跳出一个二维码,用手机微信扫描登录即可
itchat.login()
#friends里面就是你的好友信息啦,一共有36个字段,包括昵称、你的备注、性别、地区、签名、头像地址等等
friends = itchat.get_friends(update=True)
df_friends = pd.DataFrame(friends)
#性别统计,0是未知,1是男生,2是女生
Sex_count = df_friends['Sex'].value_counts()
plt.figure(figsize=(16,8)) #设置图片大小
labels = ['male','female','unknown']
colors = ['red','yellowgreen','lightskyblue']
#画性别分布饼图
plt.pie(Sex_count,colors=colors,labels=labels,autopct = '%3.1f%%',startangle = 90,pctdistance = 0.8)
# 设置x,y轴刻度一致,这样饼图才能是圆的
plt.axis('equal')
plt.legend(loc='left')
# plt.show() #这个注释打开,下面无法保存图片
plt.savefig('好友性别比例.jpg')
'''获取好友的省份和地区分布'''
Province = df_friends.Province
Province_count = Province.value_counts()
#有一些好友地理信息为空,过滤掉这一部分人
Province_count = Province_count[Province_count.index!='']
df_province =DataFrame(Province_count)
df_province.to_csv('省份分布.csv',encoding='utf-8')
City = df_friends.City
City_count = City.value_counts()
City_count = City_count[City_count.index!='']
#统计好友基本信息
number_of_friends = len(friends)
NickName = friends[0]['NickName'] #获取自己的昵称
file_name_all = NickName+'_basic_inf.txt'
with open(file_name_all,'w') as f:
f.write('你共有%d个好友,其中有%d个男生,%d个女生,%d未显示性别。\n\n' %(number_of_friends, Sex_count[1], Sex_count[2], Sex_count[0]))
f.write('你的朋友主要来自省份:%s(%d)、%s(%d)和%s(%d)。\n\n' %(Province_count.index[0],Province_count[0],Province_count.index[1],
Province_count[1],Province_count.index[2],Province_count[2]))
f.write('主要来自这些城市:%s(%d)、%s(%d)、%s(%d)、%s(%d)、%s(%d)和%s(%d)。'%(City_count.index[0],City_count[0],City_count.index[1],
City_count[1],City_count.index[2],City_count[2],City_count.index[3],City_count[3],City_count.index[4],City_count[4],City_count.index[5],City_count[5]))
# -*- coding:utf-8 -*-
import jieba,re,itchat
import numpy as np
from collections import defaultdict
from wordcloud import WordCloud, ImageColorGenerator
import PIL.Image as Image
import matplotlib.pyplot as plt
from pandas import DataFrame
import pandas as pd
#此时稍微等一会,会跳出一个二维码,用手机微信扫描登录即可
itchat.login()
#friends里面就是你的好友信息啦,一共有36个字段,包括昵称、你的备注、性别、地区、签名、头像地址等等
friends = itchat.get_friends(update=True)
df_friends = pd.DataFrame(friends)
Signatures = df_friends.Signature
regex1 = re.compile('<span.*?</span>') #匹配表情
regex2 = re.compile('\s{2,}')#匹配两个以上占位符。
#用一个空格替换表情和多个空格。
Signatures = [regex2.sub(' ',regex1.sub('',signature,re.S)) for signature in Signatures]
Signatures = [signature for signature in Signatures if len(signature)>0] #去除空字符串
text = ' '.join(Signatures)
wordlist = jieba.cut(text, cut_all=False)
def statistics(lst) :
dic = {}
for k in lst:
if not k.decode('utf-8') in dic :
dic[k.decode('utf-8')] = 0
dic[k.decode('utf-8')] +=1
return dic
worddic = statistics(wordlist)
coloring = np.array(Image.open("./xiaodong.jpg"))#词云的背景和颜色,需要提前自己找好
my_wordcloud = WordCloud(background_color="white", max_words=2000,
mask=coloring, max_font_size=200, random_state=8, scale=2,
font_path="./songti.otf").generate_from_frequencies(worddic)
image_colors = ImageColorGenerator(coloring)
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
my_wordcloud.to_file('签名分词.png')
#---------------------------------------------------
'''换一种词云产生方式,将关键词放大比例显示'''
word_space_split = ' '.join(wordlist)
coloring = np.array(Image.open("./xiaodong.jpg")) #词云的背景和颜色。这张图片在本地。
my_wordcloud = WordCloud(background_color="white", max_words=2000,
mask=coloring, max_font_size=60, random_state=42, scale=2,
font_path="./songti.otf").generate(word_space_split)
my_wordcloud.to_file('关键词签名分词.jpg') #保存图片
#--------------------------------------昵称云图-------------------------------------------------------
Nicknames = df_friends.NickName
regex1 = re.compile('<span.*?</span>') #匹配表情
regex2 = re.compile('\s{2,}')#匹配两个以上占位符。
#用一个空格替换表情和多个空格。
Nicknames = [regex2.sub(' ',regex1.sub('',nickname,re.S)) for nickname in Nicknames]
Nicknames = [nickname for nickname in Nicknames if len(nickname)>0] #去除空字符串
text_nicknames = ''.join(Nicknames)
a = re.compile(' ')
text_nicknames = a.sub('',text_nicknames)
def save_chinese(text):
text = text.decode('utf-8')
a = re.compile(u"[\u4E00-\u9FA5]+")
text = a.findall(text)
text=''.join(text)
return text
text_nicknames = save_chinese(text_nicknames)
def get_count(Sequence):
counts = defaultdict(int) #初始化一个字典
for x in Sequence:
counts[x] += 1
return counts
nickname_count = get_count(text_nicknames)
#nickname_count_s = sorted(nickname_count.iteritems(), key=lambda d:d[1], reverse = True)
coloring = np.array(Image.open("./xiaodong.jpg"))#词云的背景和颜色,需要提前自己找。
nm_wordcloud = WordCloud(background_color="white", max_words=2000,
mask=coloring, max_font_size=200, random_state=8, scale=2,
font_path="./songti.otf").generate_from_frequencies(nickname_count)
# image_colors = ImageColorGenerator(coloring)
#plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(nm_wordcloud)
plt.axis("off")
plt.show()
nm_wordcloud.to_file('昵称云图.png')
# -*- coding:utf-8 -*-
import itchat,math,os
import PIL.Image as Image
itchat.auto_login()
friends = itchat.get_friends(update=True)[0:]
user = friends[0]["UserName"]
num = 0
for i in friends:
img = itchat.get_head_img(userName=i["UserName"])
fileImage = open(r'./img/'+ str(num) + ".jpg",'wb')
fileImage.write(img)
fileImage.close()
num += 1
ls = os.listdir(r'./img/')
each_size = int(math.sqrt(float(640*640)/len(ls)))
lines = int(640/each_size)
image = Image.new('RGBA', (640, 640))
x = 0
y = 0
for i in range(0,len(ls)+1):
try:
img = Image.open(r'./img/'+ str(i) + ".jpg")
except IOError:
print("Error")
else:
img = img.resize((each_size, each_size), Image.ANTIALIAS)
image.paste(img, (x * each_size, y * each_size))
x += 1
if x == lines:
x = 0
y += 1
image.save(r'./img/'+ "all.jpg")
itchat.send_image(r'./img/'+ "all.jpg", 'filehelper')
参考:https://zhuanlan.zhihu.com/p/26514576 https://zhuanlan.zhihu.com/p/33230381