17 Python 使用API

17.1.3 安装requests

pip install --user requests

# 17.1.4 处理API响应

# 执行API调用并储存响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
status_code = r.status_code
print("status_code:" + str(status_code))
# 将API响应储存在一个变量中
response_dict = r.json()
# 处理结果
print(response_dict.keys())

运行结果

# 17.1.5 处理响应字典

# 执行API调用并储存响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
status_code = r.status_code
print("status_code:" + str(status_code))
# 将API响应储存在一个变量中
response_dict = r.json()
# 获取Github上总共多少Python仓库
total_count = response_dict['total_count']
print("total_count:" + str(total_count))
# 搜索仓库有关的信息
repo_dicts = response_dict['items']
# 研究第一个仓库
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('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'])

运行结果

# 17.1.6 概述最受欢迎的仓库

# 执行API调用并储存响应
import requests

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
# 将API响应储存在一个变量中
response_dict = r.json()
# 研究仓库有关信息
repo_dicts = response_dict['items']
print("Response 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('Starts', repo_dict['stargazers_count'])
    print('repository', repo_dict['html_url'])
    print('Description', repo_dict['description'])

运行结果

# 17.2 使用Pygal可视化仓库

# 有了一些有趣的数据后,我们来进行可视化,呈现GitHub上Python项目的受欢迎程度。我们将创建一个交互式条形图:条形的高度表示项目获得了多少颗星。单击条形将带你进入
# 项目在GitHub上的主页。
import pygal
import requests
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
status_code = r.status_code
print('status_code:', status_code)

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

# 研究仓库的有关信息
repo_dicts = response_dict["items"]
names, stars = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict["name"])
    stars.append(repo_dict["stargazers_count"])

# 可视化,将基色设置为深蓝色
my_style = LS("#333366", base_style=LCS)
# 创建一个简单的条形图,生成svg图像,x_label_rotation:让标签绕x轴旋转45度,show_legend:隐藏图例
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")

运行结果

如果将show_legend 设置为True,运行结果

 

如果将show_legend 设置为True,同时设置chart.add("标签", stars),运行结果

# 17.2.2 添加自定义工具提示

# 在Pygal中,将鼠标指向条形将显示它表示的信息,这通常称为工具提示 。
# 在这个示例中,当前显示的是项目获得了多少个星。下面来创建一个自定义工具提示,以同时显示项目的描述

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 django.'},
              {'value': 14798, 'label': 'Description of flask.'}]
chart.add('', plot_dicts)
chart.render_to_file("bar_description.svg")

运行结果

 

#17.2.3 根据数据绘图

# 为根据数据绘图,我们将自动生成plot_dicts
import pygal
import requests
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
status_code = r.status_code
print('status_code:', status_code)
# 将API响应储存在一个变量中
response_dict = r.json()
print("Total repository:", response_dict["total_count"])

# 研究仓库的有关信息
repo_dicts = response_dict["items"]
print("Number of items:", len(repo_dicts))
names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict["name"])
    #label:使用str(repo_dict['description']),如果不使用str封装
    # 报NoneType' object has no attribute 'decode'的异常了
    plot_dict = {"value": repo_dict["stargazers_count"],
                 "label": str(repo_dict["description"])}
    plot_dicts.append(plot_dict)

# 可视化
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('标签', plot_dicts)
chart.render_to_file("python_repos.svg")

运行结果

#17.2.4在图表中添加可单击的链接

#Pygal还允许你将图表中的每个条形用作网站的链接。为此,只需添加一行代码,在为每个项目创建的字典中,添加一个键为'xlink' 的键—值对:
...
plot_dict = {"value": repo_dict["stargazers_count"],
             "label": str(repo_dict["description"]),
             "xlink":repo_dict["html_url"]}
....
#可视化
...

运行结果

点击条目就自动跳转xlink地址了

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值