# Python入门与实践 第17章_使用API
# 本章中,你将学习如何编写一个独立的程序,并对其获取的数据进行可视化。这个程序将使用web
# 应用编程接口(API)自动请求网站的特定信息而不是整个网页,在对这些信息进行可视化。
# 由于这样编写的程序时钟使用最新的数据来生成可视化,因此即便数据瞬息万变,它呈现的信息
# 也都是最新的。
# 17.1 使用Web API
# Web API 是网站的一部分,用于与使用非常具体的URL请求特定信息的程序交互。这种请求称为
# API调用。请求的数据将以易于处理的格式(如JSON或CSV)返回。依赖于外部数据源的大多数应
# 用程序都依赖于API调用,如集成社交媒体网站的应用程序。
# 17.1.1 Git和GitHub
# 本章的可视化将基于来自GitHub的信息,这是一个让程序员能够协作开发项目的网站。我们将使
# 用GitHub的API来请求有关该网站中Python项目的信息,然后使用Pygal生成交互式可视化,以
# 呈现这些项目的受欢迎程度。
#GitHub(https://www.github.com)的名字源自Git,Git是一个分布式版本控制系统,让程序员
# 团队能够协作开发项目。
# 17.1.2 使用API调用请求数据
# GitHub的API让你能够通过API调用来请求各种信息。要知道API调用是什么样的,请在浏览器的
# 地址栏中输入如下地址并按回车键:
https://api.github.com/search/repositories?q=language:python&sort=stars
# 17.1.3 安装requests
# requests包让python程序能够轻松地向网站请求信息以及检查返回的响应。要安装requests,请
# 执行类似于下面的命令:
$ pip install --user requests
# 17.1.4 处理API响应
# 下面来编写一个程序,它执行API调用并处理结果,找出GitHub上星级最高的Python项目:
# python——repos.py
import requests
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:",r.status_code)
# 将API响应存储在一个变量中
response_dict = r.json()
# 处理结果
print(response_dict.keys())
# 17.1.5 处理响应字典
# 将API调用返回的信息存储到字典中后,就可以处理这个字典中的数据了。下面来生成一些概述
# 这些信息的输出。这是一种不错的方式,可确认收到了期望的信息,进而可以开始研究感兴趣的
# 信息:
# python_repos.py
import requests
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("status code:",r.status_code)
# 将API响应存储在一个变量中
response_dict = r.json()
print("Total respositories: ",response_dict['total_count'])
# 探索有关仓库的信息
repo_dicts = response_dict['items']
print("Repositories returned:",len(repo_dicts))
# 研究第一个仓库
repo_dict = repo_dicts[0]
print("\nkeys:",len(repo_dict))
for key in sorted(repo_dict.keys()):
print(key)
# 17.1.6 概述最受欢迎的仓库
# 对这些数据进行可视化时,我们需要涵盖多个仓库。下面就来编写一个循环,打印API调用返回
# 的每个仓库的特定信息,以便能够在可视化中包含所有这些信息:
--snip--
# 研究有关仓库的信息
repo_dicts = response_dict['items']
print('Repositores returned:',len(repo_dicts))
print('\nSelected information about each repository:')
for repo_dict in repo_dicts:
print('\nName:',repo_dict['name'])
print('Owner:',repo_dict['owner']['login'])
print('Stars:',repo_dict['stargazers_count'])
print('Repository:',repo_dict['html_url'])
print('Created:',repo_dict['created_at'])
print('Updated:',repo_dict['updated_at'])
print('Description:',repo_dict['description'])
# 扩展练习,通过更改语句,将上述输出信息保存在文本文件中:
--snip--
txt = open('github.txt','w')
print("项目合计:",len(repo_dicts),"个",file=txt)
for repo_dict in repo_dicts:
try:
print('Name:',repo_dict['name'],file=txt)
print('Owner:',repo_dict['owner']['login'],file=txt)
print('Stars:',repo_dict['stargazers_count'],file=txt)
print('Repository:',repo_dict['html_url'],file=txt)
print('Created:',repo_dict['created_at'],file=txt)
print('Updated:',repo_dict['updated_at'],file=txt)
print('Description:',repo_dict['description'],file=txt)
print("",file=txt)
except UnicodeEncodeError:
continue
txt.close()
# 17.1.7 监视API的速率限制
# 大多数API都存在速率限制,即你在特定时间内可执行的请求数存在限制。要获悉你是否接近了
# GitHub的限制,请在浏览器中输入https://api.github.com/rate_limit:
# 17.2 使用pygal可视化仓库
# 有了一些有趣的数据后,我们来进行可视化,呈现GitHub上python项目的受欢迎程度。我们将创
# 建一个交互式条形图:条形的高度表示项目获得了多少颗星。单击条形将带你进入项目在GitHub
# 上的主页。
# python_repos.py
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightStyle as LS
# 执行API调用并存储响应
url = "https://api.github.com/search/repositories?q=language:python&sort=satars"
r = requests.get(url)
print("Status code",r.status_code)
# 将API响应存储在一个变量中
response_dict = r.json()
# 研究有关仓库信息
response_dicts = response_dict[items]
names,stars = [],[]
for repo_dict in response_dicts:
names.append(repo_dict['name'])
stars.append(repo_dict['stargazers_count'])
# 可视化
my_style = LS('#333366',base_style=LCS)
chart = pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title = "Most-Starred Python Projects on GitHub"
chart.x_labels = names
chart.add('',stars)
chart.render_to_file('python_repos.svg')
# 17.2.1 改进pygal图表
# 改进图表样式,进行多个定制,先微调整体代码结构,创建一个配置对象,在其中包含要传递给
# Bar()的所有定制:
--snip--
#可视化
my_style = LS('#333366',base_style=LCS) # 定义条形图中条形的底色为蓝色和base_style灰色
my_config = pygal.Config() # 创建PygalConfig的实例,修改my_config,可定制图表外观。
my_config.x_label_rotation = 45 # X轴标签,绕x轴顺时针45°旋转
my_config.show_legend = False # 隐藏图例
my_config.title_font_size = 24 # 标题大小
my_config.label_font_size = 14 # X轴、y轴标签字体大小
my_config.major_label_font_size = 18 # y轴标签上刻度字体大小
my_config.truncate_label = 15 # X轴标签长度15个字符
my_config.show_y_guides = False # 隐藏图表水平线
my_config.width = 1000 # 自定义图表宽度
chart = pygal.Bar(my_config,style=my_style)
chart.title = 'Most-Starred Python Projects on Github'
chart.x_labels = names
chart.add("",stars)
chart.render_to_file("python_repos_new.svg")
# 17.2.2 添加自定义工具提示
# 在Python中,将鼠标指向条形将显示它表示的信息,这通常称为:工具提示。
# 在上面实例中,显示的是项目获得了多少个星。
# 下面创建自定义工具提示,显示项目描述:
# 示例:下面可视化前三个项目,并给每个项目对应的条形都指定自定义标签。为此,我们想add()
# 传递一个字典列表,而不是值列表:
# bar_description.py
import pygal
from pygal.style import LightColorizedStyle as LCS,lightenStyle as LS
my_style = LS('#333366',base_style=LCS)
chart = pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title = 'Python Projects'
chart.x_labels = ['httpie','django','flask']
plot_dicts = [
{'value':16101,'label':'Description of httpie.'},
{'value':15028,'label':'Description of diango.'},
{'value':14798,'label':'Description of flask.'},
]
chart.add('',plot_dicts)
chart.render_to_file('bar_description.svg')
python入门与实践-17章-使用API
最新推荐文章于 2022-07-01 20:59:42 发布