前幾天無意中看到了一片文章,《用 Python 爬了爬自己的微信朋友(實(shí)例講解)》,這篇文章寫的是使用python中的itchat爬取微信中朋友的信息,其中信息包括,昵稱、性別、地理位置等,然后對這些信息進(jìn)行統(tǒng)計(jì)并且以圖像形式顯示。文章對itchat的使用寫的很詳細(xì),但是代碼是貼圖,畫圖使用R中的包畫,我對著做了一遍,并且把他沒有貼畫圖的代碼做了一遍,畫圖是使用matplotlib。由于他沒有貼代碼,所以我把我寫的貼出來供以后復(fù)制。
首先是安裝itchat的包,可以使用清華大學(xué)的鏡像:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple itchat
爬取微信好友男女比例:
import itchat itchat.login()friends=itchat.get_friends(update=True)[0:]male=female=other=0for 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))print("顯示圖如下:")畫圖:柱狀圖和餅狀圖,圖片如下:

import numpy as npimport matplotlib.pyplot as pltimport matplotlib as mpl#解決中文亂碼不顯示問題mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默認(rèn)字體 mpl.rcParams['axes.unicode_minus'] = False #解決保存圖像是負(fù)號'-'顯示為方塊的問題 map = { 'Female': (malecol, '#7199cf'), 'Male': (femalecol, '#4fc4aa'), 'other': (othercol, '#e1a7a2')} fig = plt.figure(figsize=(5,5))# 整體圖的標(biāo)題ax = fig.add_subplot(111)#添加一個(gè)子圖ax.set_title('Gender of friends') xticks = np.arange(3)+0.15# 生成x軸每個(gè)元素的位置bar_width = 0.5# 定義柱狀圖每個(gè)柱的寬度names = map.keys()#獲得x軸的值values = [x[0] for x in map.values()]# y軸的值colors = [x[1] for x in map.values()]# 對應(yīng)顏色 bars = ax.bar(xticks, values, width=bar_width, edgecolor='none')# 畫柱狀圖,橫軸是x的位置,縱軸是y,定義柱的寬度,同時(shí)設(shè)置柱的邊緣為透明ax.set_ylabel('Proprotion')# 設(shè)置標(biāo)題ax.set_xlabel('Gender')ax.grid()#打開網(wǎng)格ax.set_xticks(xticks)# x軸每個(gè)標(biāo)簽的具體位置ax.set_xticklabels(names)# 設(shè)置每個(gè)標(biāo)簽的名字ax.set_xlim([bar_width/2-0.5, 3-bar_width/2])# 設(shè)置x軸的范圍ax.set_ylim([0, 100])# 設(shè)置y軸的范圍for bar, color in zip(bars, colors): bar.set_color(color)# 給每個(gè)bar分配指定的顏色 height=bar.get_height()#獲得高度并且讓字居上一點(diǎn) plt.text(bar.get_x()+bar.get_width()/4.,height,'%.2f%%' %float(height))#寫值plt.show()#畫餅狀圖fig1 = plt.figure(figsize=(5,5))# 整體圖的標(biāo)題ax = fig1.add_subplot(111)ax.set_title('Pie chart')labels = ['{}/n{} %'.format(name, value) for name, value in zip(names, values)]ax.pie(values, labels=labels, colors=colors)#并指定標(biāo)簽和對應(yīng)顏色plt.show()爬取其他信息,對省份分類并根據(jù)個(gè)數(shù)對其排序
#用來爬去各個(gè)變量def get_var(var): variable=[] for i in friends: value=i[var] variable.append(value) return variable #調(diào)用函數(shù)得到各個(gè)變量,并把數(shù)據(jù)存到csv文件中,保存到桌面NickName=get_var('NickName')Sex=get_var('Sex')Province=get_var('Province')City=get_var('City')Signature=get_var('Signature') pros=set(Province)#去重prosarray=[]for item in pros: prosarray.append((item,Province.count(item)))#獲取個(gè)數(shù)def by_num(p): return p[1]prosdsored=sorted(prosarray,key=by_num,reverse=True)#根據(jù)個(gè)數(shù)排序畫省份圖:

#畫圖figpro = plt.figure(figsize=(10,5))# 整體圖的標(biāo)題axpro = figpro.add_subplot(111)#添加一個(gè)子圖axpro.set_title('Province')xticks = np.linspace(0.5,20,20)# 生成x軸每個(gè)元素的位置bar_width = 0.8# 定義柱狀圖每個(gè)柱的寬度pros=[]values = []count=0for item in prosdsored: pros.append(item[0]) values.append(item[1]) count=count+1 if count>=20: break colors = ['#FFEC8B','#FFE4C4','#FFC125','#FFB6C1','#CDCDB4','#CDC8B1','#CDB79E','#CDAD00','#CD96CD','#CD853F','#C1FFC1','#C0FF3E','#BEBEBE','#CD5C5C','#CD3700','#CD2626','#8B8970','#8B6914','#8B5F65','#8B2252']# 對應(yīng)顏色 bars = axpro.bar(xticks, values, width=bar_width, edgecolor='none')axpro.set_ylabel('人數(shù)')# 設(shè)置標(biāo)題axpro.set_xlabel('省份')axpro.grid()#打開網(wǎng)格axpro.set_xticks(xticks)# x軸每個(gè)標(biāo)簽的具體位置axpro.set_xticklabels(pros)# 設(shè)置每個(gè)標(biāo)簽的名字axpro.set_xlim(0,20)# 設(shè)置x軸的范圍axpro.set_ylim([0, 100])# 設(shè)置y軸的范圍 for bar, color in zip(bars, colors): bar.set_color(color)# 給每個(gè)bar分配指定的顏色 height=bar.get_height()#獲得高度并且讓字居上一點(diǎn) plt.text(bar.get_x()+bar.get_width()/4.,height,'%.d' %float(height))#寫值 plt.show()還可以對數(shù)據(jù)進(jìn)行保存:可用excel打開
#保存數(shù)據(jù)from pandas import DataFramedata={'NickName':NickName,'Sex':Sex,'Province':Province,'City':City,'Signature':Signature}frame=DataFrame(data) frame.to_csv('data.csv',index=True)以上這篇itchat和matplotlib的結(jié)合使用爬取微信信息的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選