python编程--API可视化数据

tech2026-03-29  1

API可视化数据

调取GitHub数据资源探索如何使用其他网站的API调用

调取GitHub数据资源

API(Application Programming Interface,应用程序接口)

数据资源

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) # 200 表示成功 response_dict = r.json() # 将API响应存储在一个变量中 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'], # 单机柱状条可以连接到GitHub的这个项目 } plot_dicts.append(plot_dict) # 绘图 my_style = LS('#333366', base_style=LCS) # 深蓝色。LightenStyle(LS) # LightColorizedStyle(LCS) my_style.title_font_size = 24 my_style.label_font_size = 14 my_style.major_label_font_size = 18 my_config = pygal.Config() my_config.x_label_rotation = 45 my_config.show_legend = False my_config.truncate_label = 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')

若运行不成功可能是GitHub下载速率限制: https://api.github.com/rate_limit

探索如何使用其他网站的API调用

Hacker News(http://news.ycombinator. com/) 下面的调用返回本书编写时最热门的文章的信息: https://hacker-news.firebaseio.com/v0/item/9884165.json

import requests from operator import itemgetter # Make an API call, and store the response. url = 'https://hacker-news.firebaseio.com/v0/topstories.json' r = requests.get(url) print("Status code:", r.status_code) # Process information about each submission. submission_ids = r.json() submission_dicts = [] for submission_id in submission_ids[:30]: # Make a separate API call for each submission. 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 = { 'title': response_dict['title'], 'link': 'http://news.ycombinator.com/item?id=' + str(submission_id), 'comments': 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'])
最新回复(0)