首页 > 编程 > Python > 正文

Python获取好友地区分布及好友性别分布情况代码详解

2019-11-25 12:26:12
字体:
来源:转载
供稿:网友

利用Python + wxpy 可以快速的查询自己好友的地区分布情况,以及好友的性别分布数量。还可以批量下载好友的头像,拼接成大图。

本次教程是基于上次机器人后的,所有依赖模块都可以复用上次的,还不知道的小伙伴可以戳这里。

python + wxpy 机器人

准备工作

  1. 编辑器
  2. 一个注册一年以上的微信号

公共部分代码

from wxpy import * // wxpy 依赖from PIL import Image  // 二维码登录依赖import os  // 本地下载依赖import mathimport webbrowserfrom 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] += 1pie = 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] += 1keys = 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获取好友地区分布及好友性别分布情况代码详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表