Excel中怎样计算面积? Excel制作计算圆面积工具的教程-英雄云拓展知识分享
132
2023-11-13
【摘要】 本书摘自《Python网络爬虫 从入门到精通》一书中第7章,第1节,吕云翔、张扬和韩延刚等编著。
7.1.2 基于Python 的微信API工具
虽然上面的程序实现了想要达到的目的,但总体来看来还很简陋,如果需要对微信中的 其他数据进行分析,就很可能需要重构绝大部分代码。另外使用 Selenium 模拟浏览器的速 度毕竟很慢,如果结合微信提供的开发者 API, 就可以达到更好的效果。如果能够直接访问 API, 这个时候的“爬虫”抓取的就是纯粹的网络通信信息,而不是网页的元素了。
itchat 是一个简洁高效的开源微信个人号接口库,仍然是通过 pip 安装(当然,也可以 直接在PyCharm 中使用GUI 安装)。itchat 的设计非常简便,比如使用 itchat 给微信文件助手 发信息:
import itchat
itchat.auto_login()
itchat.send('Hello',toUserName='filehelper')
auto_login()方法即微信登录,可附带 hotReload 参数和 enableCmdQR 参数。如果设置为 true 即分别开启短期免登录和命令行显示二维码功能。具体来说,如果给 auto_login()方法传 入值为真的 hotReload 参数,即使程序关闭, 一定时间内重新开启也可以不用重新扫码。该 方法会生成一个静态文件 itchat.pkl, 用于存储登录的状态。如果给 auto_login()方法传入值为 真的 enableCmdQR 参数,那么就可以在登录的时候使用命令行显示二维码。这里需要注意
的是,默认情况下控制台背景色为黑色,如果背景色为浅色(白色),可以将 enableCmdQR
赋值为负值。
get_friends() 方法可以帮助开发者轻松获取所有的好友(其中好友首位是自己,如果不设 置 update 参数会返回本地的信息):
friends =itchat.get_friends(update=True)
借助 pyplot 模块以及上面介绍的 itchat 使用方法,就能够编写一个简洁实用的微信好友
性别分析程序:
【例7-2】 itchatWX.py,使用第三方库分析微信数据。
import itchat
from collections import Counter
import matplotlib.pyplot as plt
import csv
from pprint import pprint
def anaSex(friends):
sexs =list(map(lambda x:x['Sex'],friends[1:]))
counts =list(map(lambda x:x[1],Counter(sexs).items()))
labels =['Unknow','Male','Female']
colors =['Grey','Blue','Pink']
plt.figure(figsize=(8,5),dpi=80)#
plt.axes(aspect=1)
#绘制饼图
plt.pie(counts,
labels=labels:
colors=colors,
labeldistance=1.1,
autopct='%3.1f%%',
shadow=False,
startangle=90,
pctdistance=0.6
)
调整绘图大小
plt.legend(loc='upper right',)
plt.title('The gender distribution of {}\'s WeChat Friends'.format(friends[0] ['NickName']))
plt.show()
def anaLoc(friends):
headers =['NickName','Province','City']
with open('location.csv','w',encoding='utf-8',newline='',)as csvFile:
writer =csv.Dictwriter(csvFile,headers)
writer.writeheader()
for friend in friends[1:]:
row ={}
row['NickName']=friend['RemarkName']
row['Province']=friend['Province']
row['City']=friend['City']
writer.writerow(row)
if name ==' main__':
itchat.auto_login(hotReload=True)
friends =itchat.get_friends(update=True)
anaSex(friends)
anaLoc(friends)
pprint(friends)
itchat.logout()
其中 anaLoc() 、anaSex() 分别为分析好友性别与分析好友地区的函数。anaSex() 会将性别 比例绘制为饼图,而 anaLoc() 函数则将好友及其所在地区信息保存至 csv 文件中。这里需要 简单说明的可能是下面的代码:
sexs =list(map(lambda x:x['Sex'],friends[1:]))
counts =list(map(lambda x:x[1],Counter(sexs).items()))
这里的 map( 是 Python 中的一个特殊函数,其原型为: map(func,*iterables), 函数执行 时对*iterables (可迭代对象)中的item 依次执行 function(item), 返回一个迭代器,之后再使 用 list() 将其转化为列表对象。lambda 可以理解为“匿名函数”,即输入x, 返 回x 的 Sex 字 段值。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们 18664393530@aliyun.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~