python數(shù)據(jù)分析--微信中的故事

這幾天研究了下python中操作微信的一個有趣的包,itchat,發(fā)現(xiàn)該包很有性格,[呲牙],隨即,便引出了如下一段故事。。。。

話說,公元2018年,深夏,在華夏魔都郊區(qū)的一個小房子里,一位青年,赤裸著上身,指尖鏗鏘有力的撞擊著機械鍵盤,發(fā)出咔咔咔咔的聲音,身旁的煙灰缸里一絲絲青煙繚繞。思想搖曳在不知名的遠方。。。(實在編不下去了,哈哈哈)

閑言少敘,先上張圖。


image.png

言歸正傳。python的itchat這個包,可以獲取到自己微信好友的基本信息,包括,微信名稱,性別,省市,個性簽名,通過這些數(shù)據(jù)結(jié)合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中(其實不用的,只是這樣做,可以在調(diào)試的過程中不用一次一次登錄微信)

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ù)信息,很凌亂,包含太多東西,如下:


image.png

我們從數(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(此步為調(diào)試方便),傳入列表,轉(zhuǎn)換為字典,用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,未設(shè)置則為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))#設(shè)置標簽顯示位置和格式
    plt.show()顯示圖片

下圖為圖片顯示,哈哈哈,第一幅圖出來了。


image.png

第二幅圖,畫兩幅柱狀圖,顯示好友省市分部,

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軸的信息旋轉(zhuǎn)60度顯示
    plt.title("Province")#設(shè)置圖片的標題
    plt.show()#顯示圖片

上圖:


image.png

省市分布套路一樣,不在重復(fù),文章已經(jīng)很長了。。。。。直接上圖吧!

image.png

接下來,就是最后一個了,作圖云,這個最神奇了。用好友的個性簽名,做一個圖片

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',  # 設(shè)置字體模式
        max_words=400,  # 設(shè)置最大字數(shù)
    ).generate(str(context_list))

    plt.figure()
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis("off")
    plt.show()
    # 保存圖片
    wordcloud.to_file('wordcloud_Signature.png')

好友名稱和個性簽名,作圖云是一個的套路啊,不重復(fù)了,哈哈哈哈,上圖上圖。


image.png

是不是很神奇呢?

哈哈,作者代碼技拙,大家多多指教。[抱拳],多多點贊哦!

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

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

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