利用Python + wxpy 可以快速的查詢自己好友的地區分布情況,以及好友的性別分布數量。還可以批量下載好友的頭像,拼接成大圖。
本次教程是基于上次機器人后的,所有依賴模塊都可以復用上次的,還不知道的小伙伴可以戳這里。
python + wxpy 機器人
準備工作
公共部分代碼
from wxpy import * // wxpy 依賴 from PIL import Image // 二維碼登錄依賴 import os // 本地下載依賴 import math import webbrowser from pyecharts import Map // 地圖展示依賴 from pyecharts import Pie // 餅狀圖依賴
1. 批量下載好友頭像
# 創建頭像存放文件夾
def avaterPath():
avaterDir = os.path.join(os.getcwd(), 'wechat')
if not os.path.exists(avaterDir):
os.mkdir(avaterDir)
return avaterDir
# 獲取所有的好友頭像并保存
def saveWxAvater(avaterDir):
bot = Bot(cache_path=True)
allFriends = bot.friends(update=True)
num = 0
for friend in allFriends:
friend.getAvatar(os.path.join(avaterDir,f'{str(num)}.jpg'))
print("好友昵稱:%s"%friend.name)
num += 1
# 拼接頭像
def joinAvatar(path):
# 獲取文件夾內頭像個數
length = len(os.listdir(path))
# 設置畫布大小
image_size = 2560
# 設置每個頭像大小
each_size = math.ceil(2560 / math.floor(math.sqrt(length)))
# 計算所需各行列的頭像數量
x_lines = math.ceil(math.sqrt(length))
y_lines = math.ceil(math.sqrt(length))
image = Image.new('RGB', (each_size * x_lines, each_size * y_lines))
x = 0
y = 0
for (root, dirs, files) in os.walk(path):
for pic_name in files:
try:
with Image.open(os.path.join(path, pic_name)) as img:
img = img.resize((each_size, each_size))
image.paste(img, (x * each_size, y * each_size))
x += 1
if x == x_lines:
x = 0
y += 1
except Exception as e:
print(F"頭像讀取失敗,錯誤:{e}")
img = image.save(os.path.join(os.getcwd(), 'wechat.png'))
print('wx好友頭像拼接完成!')
if __name__ == '__main__':
avatarDir = avaterPath()
saveWxAvater(avatarDir)
joinAvatar(avatarDir)
2. 獲取好友性別分布
bot = Bot(cache_path=True) # 彈出二維碼登錄微信,生成bot對象
allFriends = bot.friends() # 獲取所有的微信好友信息
type = ['男同學','女同學','外星人'] # 男/女/未知性別好友名稱
v = [0, 0, 0] # 初始化對象好友數量
# 遍歷所有好友,判斷該好友性別
for friend in friends:
if friend.sex == 1:
v[0] += 1
elif friend.sex == 2:
v[1] += 1
else:
v[2] += 1
pie = Pie("好友性別分布")
pie.add("", type, v, is_label_show=True)
pie.render("sex.html")
webbrowser.open('sex.html')
效果

3. 獲取好友地區分布情況
代碼部分:
bot = Bot(cache_path=True) # 彈出二維碼登錄微信,生成bot對象
allFriends = bot.friends() # 獲取所有的微信好友信息
areaDic = {} # 定義一個空字典,用于存放省市以及省市人數
for friend in allFriends:
if friend.province not in areaDic:
areaDic[friend.province] = 1
else:
areaDic[friend.province] += 1
keys = area_dic.keys()
v = area_dic.values()
map = Map("好友地域分布", width=1200, height=600)
map.add("好友地域分布" ,keys, v, maptype='china', is_visualmap=True)
map.render("area.html")
webbrowser.open("area.html")
總結
以上所述是小編給大家介紹的Python獲取好友地區分布及好友性別分布情況代碼詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。