17-1其他语言
修改python_repos.py中的API调用,使其生成的图表中显示用其他语言编写的最受欢迎的项目。只需要修改url里的语言信息及图的相关信息即可生成其他语言的直方图。
python_repos.py
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:Java&sort=stars'
r = requests.get(url)
# 状态为200表示访问成功
print("Status code:", r.status_code)
# 将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
# 探索有关仓库的信息
repo_dicts = response_dict['items']
names, plot_dicts = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
description=repo_dict['description']
if not description:
description='No description provided.'
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': description,
'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.truncate_label = 15
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.show_y_guides=False
chart = pygal.Bar(my_config, style=my_style)
chart.title = "Most-Starred Java Projects on GitHub"
chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('java_repos.svg')
17-2最活跃的讨论
使用hn_submissions.py中的数据,创建一个条形图,显示Hacker News上当前最活跃的讨论。
import requests
from operator import itemgetter
import pygal
from pygal.style import LightenStyle as LS
# 执行API调用并存储响应
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print("Status code:", r.status_code)
# 处理有关每篇文章的信息
submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:30]:
# 对于每篇文章,都执行一个API调用
url = ('https://hacker-news.firebaseio.com/v0/item/' +
str(submission_id) + '.json')
submission_r = requests.get(url)
# print(submission_r.status_code)
response_dict = submission_r.json()
submission_dict = {
'label': response_dict['title'],
'xlink': 'http://news.ycombinator.com/item?id=' + str(submission_id),
'value': response_dict.get('descendants', 0)
}
submission_dicts.append(submission_dict)
# submission_dicts = sorted(submission_dicts, key=itemgetter('comments'),reverse=True)
# for submission_dict in submission_dicts:
# print("\nTitle:",submission_dict['title'])
# print("Discussion link:",submission_dict['link'])
# print("Comments:",submission_dict['comments'])
# 绘制条形图显示Hacker News上当前最活跃的讨论
my_style = LS('#333366')
my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.truncate_label = 15
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.show_y_guides = False
chart = pygal.Bar(my_config, style=my_style)
chart.title = "Most-active news on Hacker News"
chart.add('', submission_dicts)
chart.render_to_file('news.svg')