用 Python 分析微信朋友

這天山哥正在看IT動(dòng)向??吹骄W(wǎng)上有人用Python和R來分析微信朋友,于是來了興趣,也玩了一把。不過不會(huì)R,于是用Python畫圖。(參考網(wǎng)址 http://www.sohu.com/a/154250476_467794

一開始是在Windows下面玩的,后來裝不了 Jieba和Wordcloud,就轉(zhuǎn)向Mac了。

第一步,安裝 itchat

要方便,你得用PIP: pip install itchat

第二步,獲取微信朋友資料,保存為JSON

import itchat
import json

if __name__ == '__main__':
    # 把獲取到的資料存為Json,那樣在之后的調(diào)試過程,不用次次連接微信
    f = open("C:\\Users\\Samuel\\Desktop\\friends.json", encoding="UTF-8", mode="w")
    itchat.login() # 這個(gè)會(huì)彈出二維碼讓你掃碼登陸微信
    friends = itchat.get_friends(update=True)[0:
![gender.png](http://upload-images.jianshu.io/upload_images/6409065-b6c686e33427cdd5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
] #取得朋友資料數(shù)組
    json.dump(friends, fp=f) # 保存為Json
    f.close()

開始玩,分析性別比例

這個(gè)是在Mac下的代碼,Windows處理中文亂碼和Mac有點(diǎn)不同,其它一樣

# coding:utf-8
import json
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties


# Define this to solve the Mac Chinese problem.. if you use english, no need
def getChineseFont():
    return FontProperties(fname='/System/Library/Fonts/PingFang.ttc')

f = open("/Users/sam/Desktop/friends.json", encoding="UTF-8", mode="r")
friends = json.load(fp=f)
f.close()
male = female = other = 0
for friend in friends[1:]:
    sex = friend["Sex"]
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other += 1
    # 計(jì)算朋友總數(shù)
total = len(friends[1:])
# 打印出自己的好友性別比例
print("男性好友: %.2f%%" % (float(male) / total * 100))
print("女性好友: %.2f%%" % (float(female) / total * 100))
print("不明性別好友: %.2f%%" % (float(other) / total * 100))

# For windows to solve the Chinese problem. No need to add `fontproperties` to the methods.
#matplotlib.rcParams['font.sans-serif'] = ['SimHei']
plt.xticks((0, 1, 2),('其它', '男', '女'), fontproperties=getChineseFont())
plt.title('微信朋友圈性別比例分析', fontproperties=getChineseFont())
plt.bar(left=(0, 1, 2), height=(other/total * 100, male/total * 100, female/total * 100), color=('yellow', 'blue', 'red'))
plt.ylabel("百分比 %",fontproperties=getChineseFont())

plt.show()

輸出結(jié)果:

男性好友: 49.50%
女性好友: 38.25%
不明性別好友: 12.25%

gender.png

再玩,微信好友個(gè)性簽名的自定義詞云圖

這個(gè)是好玩的東東,原參考文章里那個(gè)地址分析的畫圖太復(fù)雜,沒有源碼,而且是R的,咱就不玩了。咱來分析一下大伙兒個(gè)性簽名時(shí)使用的高頻詞語是什么,做個(gè)詞云圖。
個(gè)性簽名(Signature)有很多本來是表情的,例如 emoji、span、class等等這些無關(guān)緊要的詞,需要先替換掉,另外,還有類似<>/= 之類的符號(hào),也需要寫個(gè)簡(jiǎn)單的正則替換掉,再把所有拼起來,得到text字串。不多說了,上代碼。
先安裝 JieBa 和 WordCloud:
pip install jieba
pip install wordcloud

# -*- coding:utf-8 -*-
# coding:utf-8
import json
import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
import PIL.Image as Image
import re

# Load the JSON file
f = open("/Users/sam/Desktop/friends.json", encoding="UTF-8", mode="r")
friends = json.load(fp=f)
f.close()

# Use the jieba to analyze the signature.
siglist = []
for i in friends:
    signature = i["Signature"].strip().replace("span","").replace("class","").replace("emoji","")
    rep = re.compile("1fd+w*|[<>/=]")
    signature = rep.sub("", signature)
    siglist.append(signature)
    text = "".join(siglist)

wordlist = jieba.cut(text, cut_all=True)
word_space_split = " ".join(wordlist)

# 這里用一張圖作底版,WordCloud會(huì)根據(jù)顏色來分布不同頻率出現(xiàn)的詞匯。
coloring = np.array(Image.open("/Users/sam/Desktop/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()

好了!大功告成!親個(gè)嘴兒!

friends.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容