Python 入门项目——《数据可视化》(四)


Python 入门项目——《数据可视化》(四)

使用 Web API

Web API 是网站的一部分,用于与使用非常具体的URL请求特定信息的程序交互。这种请求成为 API 调用。请求的数据将以易于处理的格式(如 json 或者 CSV)返回。。依赖外部数据源的大多数应用程序都依赖于 API 调用,如集成社交媒体网站的应用程序。

Git 和 GitHub

对于在 GitHub 上的项目,用户如果喜欢一个项目,可以给它加星(star)以表示支持,用户还可以跟踪他可能想使用的项目。在本章中,我们将编写一个程序,它能够自动下载 GitHub 上星级最高的 Python 项目信息,并将这些信息进行可视化。

使用 API 调用请求数据

GitHub 的 API 能够让你通过调用它们来请求各种信息。要知道 API 的调用是什么样,主需要访问以下链接即可:
GitHub API 链接
这个链接的调用将返回 GitHub 当前托管了多少个 Python 项目,还有有关最受欢迎的 Python 仓库的信息。下面来研究一下这个调用。第一部分 (https://api.github.com/) 将请求发送到 GitHub 网站上响应 API 调用的部分;接下来的 (search/repositories)让 API 搜索 GitHub 上的所有仓库。

repositories 后面的问号指出我们要传递一个实参。 q 表示查询,而等号让我们能够开始制定查询 q= 。通过使用 language:python ,我们制定只想获取主要语言为 Python 的仓库的信息。最后一部分 &sort=stars 制定将项目按照获得星级进行排序。
如下显示网站的响应结果:
在这里插入图片描述

安装 requests

requests 包可以使得 Python 程序能够轻松地向网站请求信息并检查返回的响应。使用以下命令来安装 request :

$ pip install --user requests

处理 API 响应

下面来编写一个程序,执行 API 调用并处理结果,找出 GitHub 上星级最高的 Python 项目:

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 响应存储在一个变量中
resquests_dict = r.json()

#处理结果
print(resquests_dict.keys())

在这里插入图片描述
状态码为200,所以请求是成功的。而响应字典只包含三个键: itemstotal_countincomplete_results

处理响应字典

将 API 调用返回的信息存储到字典中后,就可以处理这个字典中的数据了。下面来生成一些概述这些信息的输出,通过确认收到的信息进而针对感兴趣的信息进行研究。代码如下:

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 响应存储在一个变量中
resquests_dict = r.json()
print("Total repositories:", resquests_dict['total_count'])

#探究有关仓库的信息
repo_dicts = resquests_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)

#处理结果
#print(resquests_dict.keys())

在这里插入图片描述
从这里能够看到获得大量的信息,repo_dict 包含 74 个 key 。通过仔细观察这些键的信息,可以大致知道可提取有关项目的哪些信息(要准确地获悉 API 返回的哪些信息,除了阅读相关文档就是研究这些请求反馈的包)。

下面来提取其中的一些键的对应的信息来观察一下。

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 响应存储在一个变量中
resquests_dict = r.json()
print("Total repositories:", resquests_dict['total_count'])

#探究有关仓库的信息
repo_dicts = resquests_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)

print("\nSelected information about first repository:")
print("Name:", repo_dict['name'])
print("Ower:", repo_dict['owner'])
print("Starts:", 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'])


在这里插入图片描述
从上面的输出中能够看出,GitHub上星级最高的项目名称是 system-design-primer, 有 112638 个用户为这个项目加星,并且能看到这个项目是 2017-02-26T16:15:28Z 时候创建的。

提取每个项目的关键信息

为了后面方便对这些数据进行可视化,这里先通过循环处理来输出每个仓库的特定信息,以便能够在可视化中包含这些信息。

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 响应存储在一个变量中
resquests_dict = r.json()
#print("Total repositories:", resquests_dict['total_count'])

#探究有关仓库的信息
repo_dicts = resquests_dict['items']
print("Repositories returned:", len(repo_dicts))

print("\nSelected information about first repository:")
for repo_dict in repo_dicts:
    print("\nName:", repo_dict['name'])
    print("Ower:", repo_dict['owner']['login'])
    print("Starts:", 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'])

在这里插入图片描述
通过打印输出能够使得你在正式编写程序代码前了解到请求返回的响应包中的各个字段的信息内容,方便进行处理。

监视 API 的速率限制

大多数 API 都存在速率限制,即在特定时间内可执行的请求数存在限制。如果要想知道你是否接近了 GitHub 的限制,可以在浏览器中输入 https://api.github.com/rate_limit ,这样能看到如下的响应:

在这里插入图片描述

这里能搞看到 search 字段中的速率限制 limit 为 10 ,说明1分钟能够进行10次请求,而 reset 字段指的是配额重置的 Unix 时间。

使用 Pygal 可视化仓库

在得到需要的数据后,就可以进行可视化显示了,从而更形象地显示 GitHub 上 Python 项目的受欢迎程度。接下来将创建一个交互式条形图:条形的高度表示项目获得了多少颗星。单击条形将进入该项目在 GitHub 上的主页。代码如下:

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

# 执行 API 调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code: ", r.status_code)

# 将 API 响应存储在一个变量中
resquests_dict = r.json()
#print("Total repositories:", resquests_dict['total_count'])

#探究有关仓库的信息
repo_dicts = resquests_dict['items']

names, starts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    starts.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-Start Python Projects on GitHub"
chart.x_labels = names

chart.add('', starts)
chart.render_to_file('python_repos.svg')

在这里插入图片描述

修改部分显示参数:

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

# 执行 API 调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code: ", r.status_code)

# 将 API 响应存储在一个变量中
resquests_dict = r.json()
#print("Total repositories:", resquests_dict['total_count'])

#探究有关仓库的信息
repo_dicts = resquests_dict['items']

names, starts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    starts.append(repo_dict['stargazers_count'])
    
# 可视化
my_style = LS('#333366', base_style=LCS)

my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000

chart = pygal.Bar(my_config, style=my_style)
#chart = pygal.Bar(style = my_style, x_label_rotation=45, show_legend=False)
chart.title = "Most-Start Python Projects on GitHub"
chart.x_labels = names

chart.add('', starts)
chart.render_to_file('new-python_repos.svg')

在这里插入图片描述

添加可以点击的网络链接

pygal 根据与键 xlink 相关联的 URL 将每个条形都转换成活跃的链接。单击图表中的任何一条形图后都将在浏览器打开一个新的标签页,并显示单击的这个项目的主页。到此,就完成了一个数据的可视化并且是交互性的图形:

可视化代码修改如下:

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

# 执行 API 调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code: ", r.status_code)

# 将 API 响应存储在一个变量中
resquests_dict = r.json()
#print("Total repositories:", resquests_dict['total_count'])

#探究有关仓库的信息
repo_dicts = resquests_dict['items']

names, plot_dicts = [], []
for repo_dict in repo_dicts:
    print("Name:", repo_dict['name'])
    names.append(repo_dict['name'])
    plot_dict = {
        'value' : repo_dict['stargazers_count'],
        'xlink' : repo_dict['html_url'],
    }
    plot_dicts.append(plot_dict)
    
# 可视化
my_style = LS('#333366', base_style=LCS)

my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000


chart = pygal.Bar(my_config, style=my_style)
#chart = pygal.Bar(style = my_style, x_label_rotation=45, show_legend=False)
chart.title = "Most-Start Python Projects on GitHub"
chart.x_labels = names


chart.add('', plot_dicts)
chart.render_to_file('plot-python_repos.svg')

在这里插入图片描述

小结

通过本章能够了解到通过使用网站 API 来编写独立的程序,自动采集所需要的数据并进行可视化显示。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值