python 图表_Python入门学习系列——使用Python调用Web API实现图表统计
使用Python調(diào)用Web API實(shí)現(xiàn)圖表統(tǒng)計(jì)
Web API:Web應(yīng)用編程接口,用于URL請求特定信息的程序交互,請求的數(shù)據(jù)大多以非常易于處理的格式返回,比如JSON或CSV等。
本文將使用Python中的requests包實(shí)現(xiàn)Web API的調(diào)用,API接口來自于GitHub提供的公用API,最后使用圖表對API調(diào)用的結(jié)果進(jìn)行圖表統(tǒng)計(jì)顯示。
API地址為:https://api.github.com/search/repositories?q=language:python&sort=stars,該調(diào)用返回GitHub當(dāng)前托管了多少個Python項(xiàng)目,包括最受歡迎的Python倉庫的信息,結(jié)果如下:
{
"total_count": 3114636,
"incomplete_results": false,
"items": [
{
"id": 21289110,
"node_id": "MDEwOlJlcG9zaXRvcnkyMTI4OTExMA==",
"name": "awesome-python",
"full_name": "vinta/awesome-python",
"private": false,
"owner": {
"login": "vinta",
"id": 652070,
"node_id": "MDQ6VXNlcjY1MjA3MA==",
"avatar_url": "https://avatars2.githubusercontent.com/u/652070?v=4",
...
使用Web API
如果想要Python調(diào)用Web API,需要使用requests包,該包用于處理網(wǎng)絡(luò)請求和返回響應(yīng)信息。可以使用pip工具輸入以下命令進(jìn)行安裝:
$ pip install --user requests
使用requests處理API響應(yīng)
import requests
#執(zhí)行API調(diào)用并存儲響應(yīng)
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
# 調(diào)用url,將響應(yīng)對象存儲在變量r中
r=requests.get(url)
# 查看請求返回的http 狀態(tài)碼,200表示請求成功
print("Stauts Code",r.status_code)
# 使用json()將API的響應(yīng)信息(json格式)轉(zhuǎn)換為一個Python字典或JSON對象
response_dict=r.json()
#處理結(jié)果
print(response_dict.keys())
執(zhí)行后,輸出結(jié)果如下:
Stauts Code 200
dict_keys(['total_count', 'incomplete_results', 'items'])
對返回的結(jié)果進(jìn)行深度處理
針對上述API返回的結(jié)果,進(jìn)一步的進(jìn)行解析,返回每一個倉庫的詳細(xì)信息。具體見代碼注釋說明:
import requests
#執(zhí)行API調(diào)用并存儲響應(yīng)
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
# 調(diào)用url,將響應(yīng)對象存儲在變量r中
r=requests.get(url)
# 查看請求返回的http 狀態(tài)碼,200表示請求成功
print("Stauts Code",r.status_code)
# 使用json()將API的響應(yīng)信息(json格式)轉(zhuǎn)換為一個Python字典或JSON對象
response_dict=r.json()
# 獲取GitHub包含的Python庫數(shù)量
print("Total repositories:",response_dict["total_count"])
#探索有關(guān)倉庫的信息,items是由多個字典組成的列表,每一個字典包含一個倉庫信息
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)
print("\nSelected information about each repository:")
# 循環(huán)遍歷獲取每一個倉庫的詳細(xì)信息
for repo_dict in repo_dicts:
# 項(xiàng)目名稱
print('\nName:', repo_dict['name'])
# 鍵owner來訪問表示所有者的字典,再使用鍵key來獲取所有者的登錄名。
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'])
上述代碼返回的結(jié)果如下:
Stauts Code 200
Total repositories: 3114623
Repositories returned: 30
Selected information about each repository:
Name: awesome-python
Owner: vinta
Stars: 56507
Repository: https://github.com/vinta/awesome-python
Created: 2014-06-27T21:00:06Z
Updated: 2018-10-21T22:26:31Z
Description: A curated list of awesome Python frameworks, libraries, software an
d resources
Name: system-design-primer
Owner: donnemartin
Stars: 50650
Repository: https://github.com/donnemartin/system-design-primer
Created: 2017-02-26T16:15:28Z
Updated: 2018-10-21T22:02:07Z
Description: Learn how to design large-scale systems. Prep for the system design
interview. Includes Anki flashcards.
Name: models
....
注意:大多數(shù)API都存在速率限制,即你在特定時間內(nèi)可執(zhí)行的請求數(shù)存在限制。要獲悉你是否接近了GitHub的限制,請?jiān)跒g覽器中輸入https://api.github.com/rate_limit,你將看到類似于下面的響應(yīng):
通過結(jié)果可以指定,極限為每分鐘10個請求。
使用Pygal對分析的結(jié)果進(jìn)行可視化
完整代碼如下所示,具體說明見代碼中的詳細(xì)注釋:
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
#執(zhí)行API調(diào)用并存儲響應(yīng)
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
# 調(diào)用url,將響應(yīng)對象存儲在變量r中
r=requests.get(url)
# 查看請求返回的http 狀態(tài)碼,200表示請求成功
print("Stauts Code",r.status_code)
# 使用json()將API的響應(yīng)信息(json格式)轉(zhuǎn)換為一個Python字典或JSON對象
response_dict=r.json()
# 獲取GitHub包含的Python庫數(shù)量
print("Total repositories:",response_dict["total_count"])
#探索有關(guān)倉庫的信息,items是由多個字典組成的列表,每一個字典包含一個倉庫信息
repo_dicts=response_dict['items']
#print("Repositories returned:",len(repo_dicts))
## 創(chuàng)建兩個空列表存儲包含在圖表中的信息,名稱用于條形圖表的標(biāo)簽,星的數(shù)量用于確定條形圖表的高度
#names,stars=[],[]
# plot_dicts用于添加自定義工具提示
names,plot_dicts=[],[]
for repo_dict in repo_dicts:
names.append(repo_dict["name"])
# 并不是每個節(jié)點(diǎn)一定有description,所以加if判斷
if repo_dict["description"]:
plot_dict={
# Pygal根據(jù)與鍵'value'相關(guān)聯(lián)的數(shù)字來確定條形的高度
'value':int(repo_dict["stargazers_count"]),
# 使用與'label'相關(guān)聯(lián)的字符串給條形創(chuàng)建工具提示
'label':repo_dict["description"],
# 為條形圖表添加可點(diǎn)擊的鏈接
'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)
#可視化,定義樣式,將其基色設(shè)置為深藍(lán)色,并傳入LightColorizedStyle
my_style=LS('#333366',base_style=LCS)
my_config = pygal.Config()
# 表示讓標(biāo)簽繞x軸旋轉(zhuǎn)45度
my_config.x_label_rotation = 45
# 表示隱藏了圖例
my_config.show_legend = False
# 圖表標(biāo)題字體大小
my_config.title_font_size = 24
# 副標(biāo)簽字體大小,包括x軸上的項(xiàng)目名以及y軸上的大部分?jǐn)?shù)字
my_config.label_font_size = 14
# 主標(biāo)簽字體大小,y軸上為5000整數(shù)倍的刻度
my_config.major_label_font_size = 18
# 將較長的項(xiàng)目名縮短為15個字符
my_config.truncate_label = 15
# 隱藏圖表中的水平線
my_config.show_y_guides = False
# 設(shè)置了自定義寬度
my_config.width = 1000
# 使用Bar()創(chuàng)建一個簡單的條形圖
# x_label_rotation=45:表示讓標(biāo)簽繞x軸旋轉(zhuǎn)45度
# show_legend=False:表示隱藏了圖例
# chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
# 將上述的配置進(jìn)行改進(jìn),分裝為一個my_config對象
# 傳遞配置設(shè)置
chart=pygal.Bar(my_config,style=my_style)
chart.title="Most-Starred Python Projects on GitHub"
chart.x_labels=names
# 暫不需要添加標(biāo)簽
#chart.add('',stars)
# 添加工具提示需要的字典列表
chart.add('',plot_dicts)
chart.render_to_file("python_repos.svg")
#print("\nSelected information about each repository:")
## 循環(huán)遍歷獲取每一個倉庫的詳細(xì)信息
#for repo_dict in repo_dicts:
# # 項(xiàng)目名稱
# print('\nName:', repo_dict['name'])
# # 鍵owner來訪問表示所有者的字典,再使用鍵key來獲取所有者的登錄名。
# 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'])
上述代碼中,使用了pygal.Bar()方法創(chuàng)建一個簡單的條形圖,并向它傳遞了my_style。同時還傳遞了另外兩個樣式實(shí)參:讓標(biāo)簽繞x軸旋轉(zhuǎn)45度(x_label_rotation=45),并隱藏了圖例(show_legend=False),因?yàn)橹辉趫D表中繪制一個數(shù)據(jù)系列。
執(zhí)行代碼顯示結(jié)果如下圖所示:
參考資源
《Python編程:從入門到實(shí)踐》
本文后續(xù)會隨著知識的積累不斷補(bǔ)充和更新,內(nèi)容如有錯誤,歡迎指正。
最后一次更新時間:2018-10-23
總結(jié)
以上是生活随笔為你收集整理的python 图表_Python入门学习系列——使用Python调用Web API实现图表统计的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “巧未能胜拙”下一句是什么
- 下一篇: ffmpeg linux安装_ffmpe