目錄
- 1.微信好友性別比例分析
- 2.好友個性簽名詞云
一個好玩的例子,分析自己的微信好友。做了兩個,一個是好友性別比例分析,另一個是好友的個性簽名做一個個性化的詞云。
這兩個實驗在好友量較多時具有一定的價值,我的好友姑且做一個測試吧。
1.微信好友性別比例分析
import itchat
# 登錄微信,需要掃描彈出的二維碼
itchat.login()
# 爬取好友信息,json字符串
friends = itchat.get_friends(update=True)[0:]
# print(friends) # 測試是否正常輸出好友
# 定義一個函數,用來爬取各個變量, return list arr
def get_var(var):
variable = []
for i in friends:
value = i[var]
variable.append(value)
return variable
Sex = get_var('Sex')
# 初始化男女性別計數器
male = female = other = 0
for sex in Sex:
if sex == 1:
male += 1
elif sex == 2:
female += 1
else:
other += 1
# 總數
total = len(friends)
maleRate = float(male)/total*100
femaleRate = float(female)/total*100
otherRate = float(other)/total*100
print('男性好友%d人,占比:%.2f%%' % (male, maleRate))
print('女性好友%d人,占比:%.2f%%' % (female, femaleRate))
print('其他性別好友%d人,占比:%.2f%%' % (other, otherRate))
# output
# 男性好友199人,占比:61.04%
# 女性好友112人,占比:34.36%
# 其他性別好友15人,占比:4.60%
我的好友這么少啊,男性還是占多數的。部分好友未設置性別屬性。
繪制比例圖
可視化展示用到了
matplotlib.pyplot
,看到有人用百度的echarts-python
,這個庫還不成熟,我用的時候遇到中文編碼錯誤,所以棄了。改用更官方更強大的matplotlib
。
# 百分比圓餅表
import matplotlib.pyplot as plt
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'male', 'female', 'other'
sizes = [maleRate, femaleRate, otherRate]
explode = (0, 0.1, 0) # 突出顯示女性比例,嘿嘿 only "explode" the 2nd slice (i.e. 'female')
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.2f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
2.好友個性簽名詞云
# coding: utf-8
import itchat
# 登錄微信,需要掃描彈出的二維碼
itchat.login()
# 爬取好友信息,json字符串
friends = itchat.get_friends(update=True)[0:]
# print(friends)
#定義一個函數,用來爬取各個變量
def get_var(var):
variable = []
for i in friends:
value = i[var]
variable.append(value)
return variable
# 調用函數得到各變量
# 個性簽名
Signature = get_var('Signature')
# 很多本來是表情的,變成了 emoji、span、class 等等這些無關緊要的詞,需要先替換掉,另外,
# 還有類似<>/= 之類的符號,也需要寫個簡單的正則替換掉,再把所有拼起來,得到 text 字串。
import re
siglist = []
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)
# 結巴分詞
import jieba
wordlist = jieba.cut(text, cut_all=True)
word_space_split = " ".join(wordlist)
# 根據自己想要的圖片、形狀、顏色畫出相似的圖形
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
import PIL.Image as Image
import os
# d = os.path.dirname(__file__)
# 可選:coloring = np.array(Image.open(os.path.join(d, '/imgs/wechat.jpg)))
coloring = np.array(Image.open("{0}/imgs/wechat.jpg".format(os.getcwd()))) # 這里的wechat.jpg可以換成其他你想呈現的效果底圖
my_wordcloud = WordCloud(background_color="white", max_words=2000,
mask=coloring, max_font_size=60, random_state=42, scale=2,
font_path="/Library/Fonts/songti.ttc").generate(word_space_split)
image_colors = ImageColorGenerator(coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
# 保存圖片,并發送到手機
my_wordcloud.to_file(os.path.join(os.getcwd(), 'output/wechat_signature_cloud.jpg'))
itchat.send_image('output/wechat_signature_cloud.jpg', 'filehelper')
<div style="text-align: center;">
底圖1:
詞云效果圖1:
底圖2:
詞云效果圖2:
</div>
本文同時發布于個人微信公眾號微信好友初步分析