itchat和matplotlib的結(jié)合使用爬取微信信息的實例
前幾天無意中看到了一片文章,《用 Python 爬了爬自己的微信朋友(實例講解)》,這篇文章寫的是使用python中的itchat爬取微信中朋友的信息,其中信息包括,昵稱、性別、地理位置等,然后對這些信息進(jìn)行統(tǒng)計并且以圖像形式顯示。文章對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=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)) print("顯示圖如下:")
畫圖:柱狀圖和餅狀圖,圖片如下:
import numpy as np import matplotlib.pyplot as plt import 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)#添加一個子圖 ax.set_title('Gender of friends') xticks = np.arange(3)+0.15# 生成x軸每個元素的位置 bar_width = 0.5# 定義柱狀圖每個柱的寬度 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è)置柱的邊緣為透明 ax.set_ylabel('Proprotion')# 設(shè)置標(biāo)題 ax.set_xlabel('Gender') ax.grid()#打開網(wǎng)格 ax.set_xticks(xticks)# x軸每個標(biāo)簽的具體位置 ax.set_xticklabels(names)# 設(shè)置每個標(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)# 給每個bar分配指定的顏色 height=bar.get_height()#獲得高度并且讓字居上一點 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ù)個數(shù)對其排序
#用來爬去各個變量 def get_var(var): variable=[] for i in friends: value=i[var] variable.append(value) return variable #調(diào)用函數(shù)得到各個變量,并把數(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)))#獲取個數(shù) def by_num(p): return p[1] prosdsored=sorted(prosarray,key=by_num,reverse=True)#根據(jù)個數(shù)排序
畫省份圖:
#畫圖 figpro = plt.figure(figsize=(10,5))# 整體圖的標(biāo)題 axpro = figpro.add_subplot(111)#添加一個子圖 axpro.set_title('Province') xticks = np.linspace(0.5,20,20)# 生成x軸每個元素的位置 bar_width = 0.8# 定義柱狀圖每個柱的寬度 pros=[] values = [] count=0 for 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軸每個標(biāo)簽的具體位置 axpro.set_xticklabels(pros)# 設(shè)置每個標(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)# 給每個bar分配指定的顏色 height=bar.get_height()#獲得高度并且讓字居上一點 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 DataFrame data={'NickName':NickName,'Sex':Sex,'Province':Province,'City':City,'Signature':Signature} frame=DataFrame(data) frame.to_csv('data.csv',index=True)
以上這篇itchat和matplotlib的結(jié)合使用爬取微信信息的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
對python_discover方法遍歷所有執(zhí)行的用例詳解
今天小編就為大家分享一篇對python_discover方法遍歷所有執(zhí)行的用例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02python使用梯度下降和牛頓法尋找Rosenbrock函數(shù)最小值實例
這篇文章主要介紹了python使用梯度下降和牛頓法尋找Rosenbrock函數(shù)最小值實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04python3 cvs將數(shù)據(jù)讀取為字典的方法
今天小編就為大家分享一篇python3 cvs將數(shù)據(jù)讀取為字典的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12