1. 程式人生 > >Python+ITchart實現微信中男女比例,城市分佈統計並可視化顯示

Python+ITchart實現微信中男女比例,城市分佈統計並可視化顯示

直接上程式碼:

 

import  itchat
import os
import csv
import pandas as pd
from pyecharts import Bar,Pie,Geo
import shutil  as sh

# 根據index列印朋友的資訊
def print_Info(friends):
    UserName = friends['UserName']
    NickName = friends['NickName']
    HeadImgUrl = friends['HeadImgUrl']
    ContactFlag = friends['
ContactFlag'] MemberCount = friends['MemberCount'] RemarkName = friends['RemarkName'] Sex = friends['Sex'] Province = friends['Province'] City = friends['City'] MemberCount=friends['MemberCount'] Signature=friends['Signature'] print('---------------UserInfo-------------
') print("UserName:", UserName) print("NickName:", NickName) print("HeadImgUrl:", HeadImgUrl) print("ContactFlag:", ContactFlag) print("MemberCount:", MemberCount) print("RemarkName:", RemarkName) print("Sex:", Sex) print("Province:", Province) print("City:", City)
print("MemberCount:", MemberCount) print("Signature:", Signature) print('---------------END-------------') return # 統計列印男女的比例,並生成Pie.html def paint_CountScan(friends,nickName,path): # 其中1為男,2為女 male=female=other=0 for i in friends[1:]: if i['Sex']==1: male+=1 elif i['Sex']==2: female+=1 else: other+=1 total=len(friends[1:]) maleScan='{:.2%}'.format(male/total) femaleScan='{:.2%}'.format(female/total) otherScan='{:.2%}'.format(other/total) print('---------------Scan-------------') print('total:',total,'\tmale:',male,'\tfemale:',female,'\tother:',other) print('maleScan:',maleScan) print('femaleScan:',femaleScan) print('otherScan:',otherScan) print('---------------END-------------') attr=['meal','female','other'] # data=[maleScan,femaleScan,otherScan] data=[male,female,other] pie=Pie("%s的Wechat男女分佈比例"%nickName,background_color="#fff") pie.add("Wechat",attr,data,is_label_show=True) pie.show_config() dir = r'%s\%s的Wechat男女分佈比例.html' % (path, nickName) pie.render(dir) return dir # 根據自己的nickName建立對應的使用者資料夾 def createDir(filename): try: os.mkdir(filename) print(filename,'資料夾建立成功') except Exception as e: print(e) print(filename, '資料夾建立失敗,可能已經存在該資料夾') return # 資料清洗,提取需要的資訊 def get_UseInfo(friends): # 讀取資訊 data = pd.DataFrame(friends) userName = data['UserName'] nickName = data['NickName'] headImgUrl = data['HeadImgUrl'] contactFlag = data['ContactFlag'] memberCount = data['MemberCount'] remarkName = data['RemarkName'] sex = data['Sex'] province = data['Province'] city = data['City'] signature = data['Signature'] # # 生成資訊csv info = {'userName': userName, 'nickName': nickName, 'remarkName': remarkName, 'sex': sex, 'province': province, 'city': city, 'signature': signature} dataFrame = pd.DataFrame(info) return dataFrame # dataFrame為提取後的資訊格式,儲存dataFrame資訊 def save_FriendsCsvFile(dataFrame,fileName,path): # 儲存資訊csv dir=r'%s\%s的朋友資訊表.csv'%(path,fileName) dataFrame.to_csv(dir,sep=',') return dir # dataFrame為提取後的資訊格式 # 統計所在城市的資訊,並儲存下來 def save_CountCityCsvFile(dataFrame,fileName,path): count = dataFrame['nickName'].groupby(dataFrame['city']).count() city=pd.DataFrame(count[1:]) dir = r'%s\%s的朋友所在城市統計表.csv' % (path, fileName) city.to_csv(dir) return dir # 根據城市的資訊CSV檔案,畫出Bar,Pie圖 def paint_CountCityCsvFile(cityPath,nickName,path): file = open(cityPath, 'r', encoding='utf-8') # 使用csv.reader讀取csvfile中的檔案 csvFile=csv.reader(file) # 讀取第一行每一列的標題 header=next(csvFile) # 將csv 檔案中的資料儲存到data中 city=[] count=[] for i in file: temp=i.split(',') city.append(temp[0]) count.append(temp[1]) # 畫圖 # 柱狀圖 bar = Bar("%s的朋友城市分佈表" % nickName, "Data from WeChart", background_color="#fff",width=1600,height=600) bar.add("City", city, count,xaxis_label_textsize=12,xaxis_rotate=30) bar.show_config() dir_Bar = r'%s\%s的朋友城市分佈表Bar.html' % (path, nickName) bar.render(dir_Bar) # 餅狀圖 pie=Pie("%s的朋友城市分佈表" % nickName, "Data from WeChart", background_color="#fff",width=1500,height=800,title_top=80,title_text_size=20) pie.add("City", city, count, is_label_show=True,radius=[0,60]) pie.show_config() dir_Pie = r'%s\%s的朋友城市分佈表Pie.html' % (path, nickName) pie.render(dir_Pie) dir=[dir_Bar,dir_Pie] return dir def copyPKL(nickName): list=os.listdir() for i in list: if i=='itchat.pkl': try: sh.copyfile('itchat.pkl',r'.\%s\itchat.pkl'%nickName) except Exception as e: print('%s資料夾不存在'%nickName) return def add_ReplaceDir(dir,dirData): defType=[type('str'),type(['str','str'])] if type(dir)== defType[0]: dirData.append(dir) elif type(dir)==defType[1]: for i in dir: dirData.append(i) else: print(dir,'的型別是',type(dir),'不是指定的型別',defType[0],defType[1]) return dirData #根據提供的路徑替換指定HTML中的標題 def replace_Title(filePath): content = [] try: for file in filePath: title=file.split('\\')[-1].split('.')[0] with open(file, 'r', encoding='Utf-8') as f: content = f.readlines() f.close() content[4] = ' <title>%s</title>\n' % title # for i in range(0,5,1): # print(content[i]) f = open(file, 'w', encoding='utf-8') for j in content: f.write(j) f.close() except Exception as e: print(filePath,'不存在') return if __name__=="__main__": # 登入 itchat.auto_login(hotReload=True) friends=itchat.get_friends(update=True) # 列印自己的資訊 user=friends[0] print_Info(user) # 建立使用者資料夾 nickName=user['NickName'] createDir(nickName) copyPKL(nickName) path='.\%s'%nickName # 獲取想要的資料 friends = itchat.get_friends(update=True) data=get_UseInfo(friends) #要替換得title的HTML檔案 reHtmlDir=[] # 畫出男女比例圖 print('----------------畫出男女比例圖------------') dir=paint_CountScan(friends, nickName, path) reHtmlPath=add_ReplaceDir(dir,reHtmlDir) print('----------------END------------') # 畫出城市統計圖 print('----------------畫出男女比例圖------------') dir=save_FriendsCsvFile(data,nickName,path) cityFilePath=save_CountCityCsvFile(data,nickName,path) dir=paint_CountCityCsvFile(cityFilePath,nickName,path) reHtmlPath = add_ReplaceDir(dir, reHtmlDir) print('----------------END------------') # 替換標題 print(reHtmlDir) replace_Title(reHtmlPath)

效果:

  

 

  

  

 

版權

作者:feiquan

出處:http://www.cnblogs.com/feiquan/

版權宣告:本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。

大家寫文都不容易,請尊重勞動成果~ 這裡謝謝大家啦(*/ω\*)