用 python 進(jìn)行微信好友信息分析
1. 使用到的庫(kù)
① wxpy:初始化微信機(jī)器人
② openpyxl:保存微信好友數(shù)據(jù)為Excel表格
③ pyecharts:生成可視化的地圖
④ wordcloud、matplotlib、jieba:生成詞云圖
【特別提醒】:pyecharts 庫(kù)用的是0.5.x版本,而在 pip 中安裝的為1.x.x版本,因此需要自行到【官網(wǎng)】中下載。
2. 基本功能
① 分析微信好友數(shù)據(jù)
② 生成詞云圖
③ 生成地圖展示
3. 代碼實(shí)現(xiàn)
此處使用類來(lái)實(shí)現(xiàn)
(1) 導(dǎo)入模塊
# 導(dǎo)入模塊 from wxpy import Bot import openpyxl from pyecharts import Map from wordcloud import WordCloud import matplotlib.pyplot as plt import jieba
(2) 初始化機(jī)器人和獲取微信好友的源信息
此處調(diào)用 Bot() 方法,需要掃碼登陸微信網(wǎng)頁(yè)版,后續(xù)操作才能進(jìn)行。
def __init__(self, ToExcelFile="", ToCityFile="", ToMapProvinceFile="", ToMapCityFile=""): ''' 初始化機(jī)器人和其他參數(shù) ''' # 初始化機(jī)器人,需要掃碼 self.bot = Bot() # 獲取我所有的微信好友信息 - 存儲(chǔ)基礎(chǔ)信息(未處理) self.allFriends_Info = self.bot.friends() # 我的微信好友個(gè)數(shù) self.allFriends_Num = len(self.allFriends_Info) # 保存微信好友信息的表格文件路徑(.xlsx) self.ExcelFile = ToExcelFile # 保存城市詞云圖的文件路徑(.png/.jpg) self.WCOfCityFile = ToCityFile # 保存省份地圖的文件路徑(.html) self.MapProvinceFile = ToMapProvinceFile # 其他可用參數(shù) self.MapCityFile = ToMapCityFile # 自動(dòng)調(diào)用run方法,使得在實(shí)例化對(duì)象后自動(dòng)運(yùn)行其他函數(shù) self.run()
(3) 統(tǒng)計(jì)和處理微信好友的信息
除了列出的還有 個(gè)性簽名、頭像等其他屬性。
def getFriendsInfo(self):
''' 獲取微信好友的全部信息 '''
# 存儲(chǔ)微信好友的信息(經(jīng)過(guò)信息處理的)
self.friendsInfo = []
# 定義列標(biāo)題
self.infoTitle = ['NickName', 'RemarkName', 'Sex', 'Province', 'City']
for aFriend in self.allFriends_Info:
# 獲取昵稱
NickName = aFriend.raw.get(self.infoTitle[0], None)
# 獲取備注
RemarkName = aFriend.raw.get(self.infoTitle[1], None)
# 獲取性別
Sex = {1:"男", 2:"女", 0:"其他"}.get(aFriend.raw.get(self.infoTitle[2], None), None)
# 獲取省份
Province = aFriend.raw.get(self.infoTitle[3], None)
# 獲取城市
City = aFriend.raw.get(self.infoTitle[4], None)
lisTmp = [NickName, RemarkName, Sex, Province, City]
self.friendsInfo.append(lisTmp)
(4) 保存微信好友的信息
在這保存為Excel表格,在代碼中插入表頭行,為了便于閱讀。
def saveFriendsInfoAsExcel(self, ExcelName):
''' 保存微信好友的信息到 Excel 表格中 '''
# 生成openpyxl對(duì)象
workbook = openpyxl.Workbook()
# 激活表格
sheet = workbook.active
# 設(shè)置表格標(biāo)題
sheet.title = 'WeChatFriendsInfo'
# 填充列標(biāo)題到第一行
for _ in range(len(self.infoTitle)):
sheet.cell(row=1, column=_+1, value=self.infoTitle[_])
# 填充微信好友信息,從第二行開(kāi)始
for i in range(self.allFriends_Num):
for j in range(len(self.infoTitle)):
sheet.cell(row=i+2, column=j+1, value=str(self.friendsInfo[i][j]))
# 若文件名非空,則保存到該路徑下
if ExcelName != "":
workbook.save(ExcelName)
print(">>> Save WeChat friends' information successfully!")
(5) 分析微信好友的信息
def quiteAnalyzeFriendsInfo(self): ''' 分析數(shù)據(jù),一步到位,直接了當(dāng) ''' print(self.allFriends_Info.stats_text())
(6) 生成city詞云圖
def creatWordCloudOfCity(self, CityName):
''' 使用獲取的數(shù)據(jù)生成city詞云圖 '''
# 獲取所有的城市
cityStr = ""
for i in range(self.allFriends_Num):
if self.friendsInfo[i][4] not in cityStr:
cityStr += " " + self.friendsInfo[i][4]
#jieba庫(kù)精確模式分詞
wordlist = jieba.lcut(cityStr)
cityStr = ' '.join(wordlist)
# 加載背景圖片
#cloud_mask = np.array(Image.open(BackGroundFile))
#設(shè)置詞云圖屬性
font = r'C:\Windows\Fonts\simfang.ttf' # 設(shè)置字體路徑
wc = WordCloud(
background_color = 'black', # 背景顏色
#mask = cloud_mask, # 背景圖片
max_words = 100, # 設(shè)置最大顯示的詞云數(shù)
font_path = font, # 設(shè)置字體形式(在本機(jī)系統(tǒng)中)
height = 300, # 圖片高度
width = 600, # 圖片寬度
max_font_size = 100, # 字體最大值
random_state = 100, # 配色方案的種類
)
# 生成詞云圖
myword = wc.generate(cityStr)
#展示詞云圖
plt.imshow(myword)
plt.axis('off')
plt.show()
# 若文件名非空,則保存到該路徑下
if CityName != "":
#保存詞云圖
wc.to_file(CityName)
print(">>> Creat WeChat wordcloud of city successfully!")
(7) 生成province地圖
def creatMapProvince(self, MapFile):
''' 使用獲取的數(shù)據(jù)生成province地圖 '''
# 獲取所有省份
provinceList, provinceNum = [], []
for i in range(self.allFriends_Num):
if self.friendsInfo[i][3] not in provinceList:
provinceList.append(self.friendsInfo[i][3])
provinceNum.append(0)
for i in range(self.allFriends_Num):
for j in range(len(provinceList)):
if self.friendsInfo[i][3] == provinceList[j]:
provinceNum[j] += 1
# 生成 Map
map = Map("各省微信好友分布", width=1000, height=800)
map.add("", provinceList, provinceNum, maptype="china", is_visualmap=True, visual_text_color='#000')
# 若文件名非空,則保存到該路徑下
if MapFile != "":
map.render(MapFile)
print(">>> Creat WeChat Map of Provinces seccessfully!")
(8) 生成city地圖
def creatMapCity(self, MapFile):
''' 使用獲取的數(shù)據(jù)生成city地圖 '''
# 獲取所有省份
CityList, CityNum = [], []
for i in range(self.allFriends_Num):
if self.friendsInfo[i][4] not in CityList:
CityList.append(self.friendsInfo[i][4])
CityNum.append(0)
for i in range(self.allFriends_Num):
for j in range(len(CityList)):
if self.friendsInfo[i][4] == CityList[j]:
CityNum[j] += 1
for i in range(len(CityList)):
CityList[i] += '市'
# 生成 Map
map = Map("各市微信好友分布", width=1000, height=800)
map.add("", CityList, CityNum, maptype="廣東", is_visualmap=True, visual_text_color='#000')
# 若文件名非空,則保存到該路徑下
if MapFile != "":
map.render(MapFile)
print(">>> Creat WeChat Map of Cities seccessfully!")
有了上述實(shí)現(xiàn)各個(gè)功能的方法,那么就差一個(gè)調(diào)用各種方法的方法了。
(9) run方法
def run(self):
# 獲取微信好友信息
self.getFriendsInfo()
print(">>> Get WeChat friends' information successfully!")
print(">>> Members:", self.allFriends_Num)
# 保存微信好友信息
self.saveFriendsInfoAsExcel(self.ExcelFile)
# 分析微信好友信息
self.quiteAnalyzeFriendsInfo()
# 使用微信好友的 city 產(chǎn)生詞云圖
self.creatWordCloudOfCity(self.WCOfCityFile)
# 生成微信好友的 province 地圖
self.creatMapProvince(self.MapProvinceFile)
# 生成微信好友的 city 地圖
self.creatMapCity(self.MapCityFile)
對(duì)于文件路徑,在main函數(shù)中傳遞即可?!咀ⅰ浚荷鲜龃a都在類中,在此處結(jié)束,下面為main函數(shù)
if __name__ == "__main__": ToExcelFile = "./WeChatAnalyze//FriendsInfo.xlsx" # 微信好友信息的Excel表格保存路徑 ToPictureFile = "./WeChatAnalyze//CityWordCloud.png" # 微信好友信息city詞云圖保存路徑 ToMapFileProvince = "./WeChatAnalyze//WeChatProvinceMap.html" # 微信好友信息province地圖保存路徑 ToMapFileCity = "./WeChatAnalyze//WeChatCityMap.html" # 微信好友信息city地圖保存路徑 # WeChatRobot對(duì)象實(shí)例化 robot = WeChatRobot(ToExcelFile, ToPictureFile, ToMapFileProvince, ToMapFileCity)
是不是覺(jué)得Main函數(shù)很簡(jiǎn)短,哈哈,沒(méi)錯(cuò),就是這么簡(jiǎn)!
接下來(lái)看看實(shí)現(xiàn)的效果吧!
>>> 這個(gè)是終端顯示效果

>>> 這個(gè)是保存為Excel表格的內(nèi)容

>>> 這個(gè)是微信好友各省的分布

>>> 這個(gè)是微信好友各市的分布

完整代碼
# -*- coding: utf-8 -*-
'''
This is a program which can analyze datas of WeChat friends.
@author: bpf
'''
# 導(dǎo)入模塊
from wxpy import Bot
import openpyxl
from pyecharts import Map
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba
class WeChatRobot:
'''====================== 1. 獲取微信好友信息 ======================'''
def __init__(self, ToExcelFile="", ToCityFile="", ToMapProvinceFile="", ToMapCityFile=""):
''' 初始化機(jī)器人和其他參數(shù) '''
# 初始化機(jī)器人,需要掃碼
self.bot = Bot()
# 獲取我所有的微信好友信息 - 存儲(chǔ)基礎(chǔ)信息(未處理)
self.allFriends_Info = self.bot.friends()
# 我的微信好友個(gè)數(shù)
self.allFriends_Num = len(self.allFriends_Info)
# 保存微信好友信息的表格文件路徑(.xlsx)
self.ExcelFile = ToExcelFile
# 保存城市詞云圖的文件路徑(.png/.jpg)
self.WCOfCityFile = ToCityFile
# 保存省份地圖的文件路徑(.html)
self.MapProvinceFile = ToMapProvinceFile
# 其他可用參數(shù)
self.MapCityFile = ToMapCityFile
# 自動(dòng)調(diào)用run方法,使得在實(shí)例化對(duì)象后自動(dòng)運(yùn)行其他函數(shù)
self.run()
'''====================== 2. 統(tǒng)計(jì)微信好友信息 ======================'''
def getFriendsInfo(self):
''' 獲取微信好友的全部信息 '''
# 存儲(chǔ)微信好友的信息(經(jīng)過(guò)信息處理的)
self.friendsInfo = []
# 定義列標(biāo)題
self.infoTitle = ['NickName', 'RemarkName', 'Sex', 'Province', 'City']
for aFriend in self.allFriends_Info:
# 獲取昵稱
NickName = aFriend.raw.get(self.infoTitle[0], None)
# 獲取備注
RemarkName = aFriend.raw.get(self.infoTitle[1], None)
# 獲取性別
Sex = {1:"男", 2:"女", 0:"其他"}.get(aFriend.raw.get(self.infoTitle[2], None), None)
# 獲取省份
Province = aFriend.raw.get(self.infoTitle[3], None)
# 獲取城市
City = aFriend.raw.get(self.infoTitle[4], None)
lisTmp = [NickName, RemarkName, Sex, Province, City]
self.friendsInfo.append(lisTmp)
'''====================== 3. 保存微信好友信息 ======================'''
def saveFriendsInfoAsExcel(self, ExcelName):
''' 保存微信好友的信息到 Excel 表格中 '''
# 生成openpyxl對(duì)象
workbook = openpyxl.Workbook()
# 激活表格
sheet = workbook.active
# 設(shè)置表格標(biāo)題
sheet.title = 'WeChatFriendsInfo'
# 填充列標(biāo)題到第一行
for _ in range(len(self.infoTitle)):
sheet.cell(row=1, column=_+1, value=self.infoTitle[_])
# 填充微信好友信息,從第二行開(kāi)始
for i in range(self.allFriends_Num):
for j in range(len(self.infoTitle)):
sheet.cell(row=i+2, column=j+1, value=str(self.friendsInfo[i][j]))
# 若文件名非空,則保存到該路徑下
if ExcelName != "":
workbook.save(ExcelName)
print(">>> Save WeChat friends' information successfully!")
'''====================== 4. 分析微信好友信息 ======================'''
def quiteAnalyzeFriendsInfo(self):
''' 分析數(shù)據(jù),一步到位,直接了當(dāng) '''
print(self.allFriends_Info.stats_text())
'''====================== 5. 產(chǎn)生city詞云圖 ======================'''
def creatWordCloudOfCity(self, CityName):
''' 使用獲取的數(shù)據(jù)生成city詞云圖 '''
# 獲取所有的城市
cityStr = ""
for i in range(self.allFriends_Num):
if self.friendsInfo[i][4] not in cityStr:
cityStr += " " + self.friendsInfo[i][4]
#jieba庫(kù)精確模式分詞
wordlist = jieba.lcut(cityStr)
cityStr = ' '.join(wordlist)
# 加載背景圖片
#cloud_mask = np.array(Image.open(BackGroundFile))
#設(shè)置詞云圖屬性
font = r'C:\Windows\Fonts\simfang.ttf' # 設(shè)置字體路徑
wc = WordCloud(
background_color = 'black', # 背景顏色
#mask = cloud_mask, # 背景圖片
max_words = 100, # 設(shè)置最大顯示的詞云數(shù)
font_path = font, # 設(shè)置字體形式(在本機(jī)系統(tǒng)中)
height = 300, # 圖片高度
width = 600, # 圖片寬度
max_font_size = 100, # 字體最大值
random_state = 100, # 配色方案的種類
)
# 生成詞云圖
myword = wc.generate(cityStr)
#展示詞云圖
plt.imshow(myword)
plt.axis('off')
plt.show()
# 若文件名非空,則保存到該路徑下
if CityName != "":
#保存詞云圖
wc.to_file(CityName)
print(">>> Creat WeChat wordcloud of city successfully!")
'''===================== 6. 產(chǎn)生province地圖 ====================='''
def creatMapProvince(self, MapFile):
''' 使用獲取的數(shù)據(jù)生成province地圖 '''
# 獲取所有省份
provinceList, provinceNum = [], []
for i in range(self.allFriends_Num):
if self.friendsInfo[i][3] not in provinceList:
provinceList.append(self.friendsInfo[i][3])
provinceNum.append(0)
for i in range(self.allFriends_Num):
for j in range(len(provinceList)):
if self.friendsInfo[i][3] == provinceList[j]:
provinceNum[j] += 1
# 生成 Map
map = Map("各省微信好友分布", width=1000, height=800)
map.add("", provinceList, provinceNum, maptype="china", is_visualmap=True, visual_text_color='#000')
# 若文件名非空,則保存到該路徑下
if MapFile != "":
#map.show_config()
map.render(MapFile)
print(">>> Creat WeChat Map of Provinces seccessfully!")
'''===================== 7. 產(chǎn)生city地圖 ====================='''
def creatMapCity(self, MapFile):
''' 使用獲取的數(shù)據(jù)生成city地圖 '''
# 獲取所有省份
CityList, CityNum = [], []
for i in range(self.allFriends_Num):
if self.friendsInfo[i][4] not in CityList:
CityList.append(self.friendsInfo[i][4])
CityNum.append(0)
for i in range(self.allFriends_Num):
for j in range(len(CityList)):
if self.friendsInfo[i][4] == CityList[j]:
CityNum[j] += 1
for i in range(len(CityList)):
CityList[i] += '市'
# 生成 Map
map = Map("各市微信好友分布", width=1000, height=800)
map.add("", CityList, CityNum, maptype="廣東", is_visualmap=True, visual_text_color='#000')
# 若文件名非空,則保存到該路徑下
if MapFile != "":
map.render(MapFile)
print(">>> Creat WeChat Map of Cities seccessfully!")
'''===================== 8. 自動(dòng)執(zhí)行函數(shù) ====================='''
def run(self):
# 獲取微信好友信息
self.getFriendsInfo()
print(">>> Get WeChat friends' information successfully!")
print(">>> Members:", self.allFriends_Num)
# 保存微信好友信息
self.saveFriendsInfoAsExcel(self.ExcelFile)
# 分析微信好友信息
self.quiteAnalyzeFriendsInfo()
# 使用微信好友的 city 產(chǎn)生詞云圖
self.creatWordCloudOfCity(self.WCOfCityFile)
# 生成微信好友的 province 地圖
self.creatMapProvince(self.MapProvinceFile)
# 生成微信好友的 city 地圖
self.creatMapCity(self.MapCityFile)
if __name__ == "__main__":
ToExcelFile = "./WeChatAnalyze//FriendsInfo.xlsx" # 微信好友信息的Excel表格保存路徑
ToPictureFile = "./WeChatAnalyze//CityWordCloud.png" # 微信好友信息city詞云圖保存路徑
ToMapFileProvince = "./WeChatAnalyze//WeChatProvinceMap.html" # 微信好友信息province地圖保存路徑
ToMapFileCity = "./WeChatAnalyze//WeChatCityMap.html" # 微信好友信息city地圖保存路徑
# WeChatRobot對(duì)象實(shí)例化
robot = WeChatRobot(ToExcelFile, ToPictureFile, ToMapFileProvince, ToMapFileCity)
以上就是用 python 進(jìn)行微信好友信息分析的詳細(xì)內(nèi)容,更多關(guān)于python 微信信息分析的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- 基于Python采集爬取微信公眾號(hào)歷史數(shù)據(jù)
- python制作定時(shí)發(fā)送信息腳本的實(shí)現(xiàn)思路
- python修改微信和支付寶步數(shù)的示例代碼
- Python爬取微信小程序通用方法代碼實(shí)例詳解
- python向企業(yè)微信發(fā)送文字和圖片消息的示例
- Python 實(shí)現(xiàn)微信自動(dòng)回復(fù)的方法
- Python selenium爬取微信公眾號(hào)文章代碼詳解
- Python爬蟲(chóng)爬取微信朋友圈
- python操作微信自動(dòng)發(fā)消息的實(shí)現(xiàn)(微信聊天機(jī)器人)
- Python Flask微信小程序登錄流程及登錄api實(shí)現(xiàn)代碼
- Python使用20行代碼實(shí)現(xiàn)微信聊天機(jī)器人
- Python實(shí)現(xiàn)清理微信僵尸粉功能示例【基于itchat模塊】
相關(guān)文章
如何使用Python的Requests包實(shí)現(xiàn)模擬登陸
這篇文章主要為大家詳細(xì)介紹了使用Python的Requests包模擬登陸,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
python自動(dòng)化運(yùn)維之Telnetlib的具體使用
本文將結(jié)合實(shí)例代碼,介紹python自動(dòng)化運(yùn)維之Telnetlib的具體使用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
python tornado開(kāi)啟多進(jìn)程的幾種方法
本文主要介紹了python tornado開(kāi)啟多進(jìn)程的幾種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
python中l(wèi)ist循環(huán)語(yǔ)句用法實(shí)例
這篇文章主要介紹了python中l(wèi)ist循環(huán)語(yǔ)句用法,以實(shí)例形式詳細(xì)介紹了Python針對(duì)list的解析,包含各種常見(jiàn)的遍歷操作及原理分析,需要的朋友可以參考下2014-11-11
Python爬蟲(chóng)實(shí)現(xiàn)全國(guó)失信被執(zhí)行人名單查詢功能示例
這篇文章主要介紹了Python爬蟲(chóng)實(shí)現(xiàn)全國(guó)失信被執(zhí)行人名單查詢功能,涉及Python爬蟲(chóng)相關(guān)網(wǎng)絡(luò)接口調(diào)用及json數(shù)據(jù)轉(zhuǎn)換等相關(guān)操作技巧,需要的朋友可以參考下2018-05-05

