這幾天研究了下python中操作微信的一個有趣的包际看,itchat,發(fā)現(xiàn)該包很有性格矢否,[呲牙]仲闽,隨即,便引出了如下一段故事僵朗。赖欣。。验庙。
話說顶吮,公元2018年,深夏粪薛,在華夏魔都郊區(qū)的一個小房子里悴了,一位青年,赤裸著上身汗菜,指尖鏗鏘有力的撞擊著機械鍵盤让禀,發(fā)出咔咔咔咔的聲音,身旁的煙灰缸里一絲絲青煙繚繞陨界。思想搖曳在不知名的遠方巡揍。。菌瘪。(實在編不下去了腮敌,哈哈哈)
閑言少敘,先上張圖俏扩。
言歸正傳糜工。python的itchat這個包,可以獲取到自己微信好友的基本信息录淡,包括捌木,微信名稱,性別嫉戚,省市刨裆,個性簽名澈圈,通過這些數(shù)據(jù)結合pandas便可以分析微信好友的性別占比,省市分部帆啃,并用好友的微信名稱和個性簽名做圖云瞬女。
第一步,先引入包
import itchat
import csv
import pandas as pd
from do_plot import Itchar_friend #在另一個文件中寫了一個類努潘,主要實現(xiàn)了一些作圖的函數(shù)接口
#在另一個文件中引入
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud
第二步诽偷,,獲取好友信息疯坤,并寫入到csv中(其實不用的报慕,只是這樣做,可以在調試的過程中不用一次一次登錄微信)
friends_items = []
itchat.login()#微信登錄
friends = itchat.get_friends()#獲取所有微信信息
print(friends)
for frident in friends:#從返回的信息中獲取好友NickName,Sex,Province,City,Signature信息
friends_item = get_some_vlaue(frident)
friends_items.append(friends_item)
print(friends_items)
用get_friends()獲取的數(shù)據(jù)信息压怠,很凌亂卖子,包含太多東西,如下:
我們從數(shù)據(jù)中獲取如下有效信息并保存在列表friends_items 中
代碼如下:
def get_some_vlaue(friend):
friend_dict = {}
NickName = friend['NickName']
Signature = friend['Signature']
Sex = friend['Sex']
Province = friend['Province']
City = friend['City']
friend_dict['NickName'] = NickName
friend_dict['Signature'] = Signature
friend_dict['Sex'] = Sex
friend_dict['Province'] = Province
friend_dict['City'] = City
return friend_dict
寫入csv(此步為調試方便)刑峡,傳入列表,轉換為字典玄柠,用pandas的方法寫入到csv中突梦。
def save_csv(friend_dict):
friend_header = friend_dict[0].keys()
NickName = []
Signature = []
Sex = []
Province = []
City = []
for friend in friend_dict:
NickName.append(friend['NickName'])
Signature.append(friend['Signature'])
Sex.append(friend['Sex'])
Province.append(friend['Province'])
City.append(friend['City'])
data = {'NickName': NickName, 'Sex': Sex, 'Province': Province,
'City': City, 'Signature': Signature}
frame = pd.DataFrame(data)
frame.to_csv('frident.csv',index=True)
return frame
第三部,分析數(shù)據(jù)羽利,畫圖宫患,
先利用pandas將數(shù)據(jù)從csv中讀出,一步步畫圖
def read_csv(self):
frame_dt = pd.read_csv("frident.csv")
print(frame_dt.head())
return frame_dt
讀入數(shù)據(jù)这弧,并返回datefream的格式返回娃闲,方便之后的數(shù)據(jù)處理
第一幅圖:性別占比圖,從接口獲取的數(shù)據(jù)中性別男匾浪,Sex為1皇帮,女為2,未設置則為0蛋辈,計算出男女人數(shù)属拾,并畫圖
def plt_sex_plant(self,frame):
sex = frame['Sex']#獲取到所有性別信息
male = famale = other = 0
for i in range(len(sex)):#計算男女人數(shù)
if sex[i] == 1:
male += 1
elif sex[i] == 2:
famale += 1
else:
other += 1
label = ['male','famale','other']
#畫餅狀圖,傳入包含人數(shù)的列表冷溶,標簽渐白,和顯示形式
plt.pie([male,famale,other],labels=label,autopct='%1.1f%%',)
plt.axis('equal')#二位形式顯示
plt.legend(loc='upper left', bbox_to_anchor=(-0.1, 1))#設置標簽顯示位置和格式
plt.show()顯示圖片
下圖為圖片顯示,哈哈哈逞频,第一幅圖出來了纯衍。
第二幅圖,畫兩幅柱狀圖苗胀,顯示好友省市分部襟诸,
def plt_province_plant(self,frame):
Province = frame['Province']#獲取省所有分布信息
name_list = set(Province)#獲取涉及的省
x_list = list(name_list)
vals = {}
#獲取每一個省的好友個數(shù)
for i in x_list:
pro_name = frame[frame['Province'] == i]#
vals[i] = len(pro_name)
#定義x,y的數(shù)據(jù)列表
x_vals = []
y_vals = []
vals_k = sorted(vals.items(), key=lambda vals: vals[1], reverse=True)#將獲取到的分部信息排序瓦堵,以從小到大的順序排序的
for vals_i in vals_k[:10]:#獲取前10位信息,顯示就好
x_vals.append(vals_i[0])
y_vals.append(vals_i[1])
#打開一個畫布
plt.figure()
plt.bar(x_vals, y_vals, width=0.8)#畫一個柱狀圖
plt.xticks(rotation=60)#x軸的信息旋轉60度顯示
plt.title("Province")#設置圖片的標題
plt.show()#顯示圖片
上圖:
省市分布套路一樣励堡,不在重復谷丸,文章已經(jīng)很長了。应结。刨疼。。鹅龄。直接上圖吧揩慕!
接下來,就是最后一個了扮休,作圖云迎卤,這個最神奇了。用好友的個性簽名玷坠,做一個圖片
def plt_Signature_plant(self,frame):
context_list = list(set(frame['Signature']))#獲取所有個性簽名信息
wordcloud = WordCloud(
width=600,
height=300,
font_path=r'D:\word\simhei.ttf', # 設置字體模式
max_words=400, # 設置最大字數(shù)
).generate(str(context_list))
plt.figure()
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()
# 保存圖片
wordcloud.to_file('wordcloud_Signature.png')
好友名稱和個性簽名蜗搔,作圖云是一個的套路啊,不重復了八堡,哈哈哈哈樟凄,上圖上圖。
是不是很神奇呢兄渺?
哈哈缝龄,作者代碼技拙,大家多多指教挂谍。[抱拳]叔壤,多多點贊哦!