获取GitHub数据方式
要想从网络获取数据,就要使用Web API,通过它可以使用非常具体的URL请求特定信息。
返回的信息通常是JSON或CSV格式,使用Python能够很方便地处理它们。
本节,我们请求的网站URL为:https://api.github.com/search/repositories?q=language:python&sort=stars
它返回GitHub当前托管Python的仓库项目和按星标排序后的数据。
返回的数据示例如下:
可见,GitHub上共有Python仓库6485042个。
Json解析
由于大部分返回的数据都是Json格式,先看一下Python处理Json数据的方式。
假设有以下格式的Json数据:
[
{
"Country Name": "Arab World",
"Country Code": "ARB",
"Year": "1960",
"Value": "96388069"
},
{
"Country Name": "Arab World",
"Country Code": "ARB",
"Year": "1961",
"Value": "98882541.4"
}
]
Python内置json库,直接使用即可。解析数据的方式如下:
import json
filename = 'demo.json'
with open(filename) as f:
pop_data = json.load(f)
for pop_dict in pop_data:
if pop_dict['Year'] == '2012':
country_name = pop_dict['Country Name']
population = pop_dict['Value']
print(country_name + ':' + population)
Python通过Web API获取数据
Python使用requests包,能够轻松向网站请求数据,以及检查返回的响应。
安装:pip install requests
使用方式如下:
import requests
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print('Status code:', r.status_code)
response_dict = r.json()
print('Total repositories:', response_dict['total_count'])
repo_dicts = response_dict['items']
print('Repositories returned:', len(repo_dicts))
for repo_dict in repo_dicts:
print('Name:', repo_dict['name'])
Pygal可视化
拿到数据后,就可以进行可视化,这样看数据的方式更直观。
我们将着手创建一个交互式条形图,条形的高度表示项目获取了多少颗星,单击条形图自动转到项目主页。
直接上代码:
#--coding: utf-8--
import requests
import pygal
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)
print('Status code:', r.status_code)
response_dict = r.json()
print('Total repositories:', response_dict['total_count'])
repo_dicts = response_dict['items']
print('Repositories returned:', len(repo_dicts))
# 存储信息,用于在图形上显示
names, plot_dicts = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': str(repo_dict['description']), # 解决 AttributeError: 'NoneType' object has no attribute 'decode'
'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 # 绕x轴旋转45度
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 10
my_config.truncate_label = 15 # 标签限制为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('', plot_dicts) # 不需要标签
chart.render_to_file('python_repos.svg')
在浏览器中打开生成的文件,得到的效果如下:
小结
Python使用Web API的方式是很方便的,处理返回数据也很容易。
借助于Pygal,可视化更是可以用几行简单的代码来实现。
本文只是一个很简单的示例,在此基础上扩展,可以做一些很有趣的项目。
参考资料
《Python编程——从入门到实践》