Python使用Pygal可视化GitHub仓库排名

获取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编程——从入门到实践》

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值