今天我们来继续处理从API获取到到数据,开始吧~
处理响应字典将API调用返回的信息存储到字典中后,就可以处理这个字典中到数据了。下面来生成一些概述这些信息的输出。这是一种不错的方式,可确认收到了期望的信息,进而可以开始研究感兴趣的信息。
import requests#执行API调用并存储响应url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'r = requests.get(url)print("Status code:",r.status_code)#将API响应存储在一个变量中response_dict = r.json()print("Total repositories:",response_dict['total_count'])#探索有关仓库的信息repo_dicts = response_dict['items']print("Repositories returned:",len(repo_dicts))#研究第一个仓库repo_dict = repo_dicts[0]print("\nKeys:",len(repo_dict))for key in sorted(repo_dict.keys()):print(key)
首先,我们打印除了与‘total_count’相关联的值,它指出了GitHub总共包含多少个Python仓库。
与item相关联的值是一个列表,其中包含很多字典,而每个字典都包含一个有关Python仓库的信息。我们将这个字典列表存储在repo_dict中。接下来,我们打印repo_dicts的长度,以获悉我们获得了多少个仓库的信息。
为更深入地了解返回的有关每个仓库的信息,我们提取了repo_dicts中的第一个字典,并将其存储在repo_dict中。接下来,我们打印这个字典包含的键数,看看其中有多少信息。最后,我们打印这个字典的所有键,看看其中包含哪些信息。
下面来提取repo_dict中与一些键相关联的值:
#研究第一个仓库repo_dict = repo_dicts[0]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'])
在这里,我们打印了表示第一个仓库的字典中与很多键相关联的值。首先我们打印了项目名称,项目所有者是用一个字典表示的,因此我们用owner来访问表示所有者的字典,再使用键key来获取所有者的登录名。接着我们打印项目获得了多少个星的评级,以及项目在GitHub仓库的URL。接下来,我们显示项目的创建时间和最后一次更新的时间。最后,打印仓库的描述。运行一下~
概述最受欢迎的仓库对这些数据进行可视化时,我们需要涵盖多个仓库。下面就来编写一个循环,打印API调用返回的每个仓库的特定信息,以便能够在可视化中包含所有这些信息。
print("\nSelected information about first repository:")for repo_dict in repo_dicts: print('Name:',repo_dict['name']) print('Owner:',repo_dict['owner']['login']) print('Stars:',repo_dict['stargazers_count']) print('Repository:',repo_dict['html_url']) print('Description:',repo_dict['description'])
首先我们打印了一条说明性消息。接着我们遍历所有字典。在这个循环中,我们打印每个项目的名称,所有者,星级,GitHub上的URL以及描述:
好了,明天开始我们进行数据可视化,期待一下~