Python調用GithubAPI並進行初步的數據分析


找到一個Github 上的公開api

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'

 

 

 網頁內容是一個巨大的Python字典,我們來獲取一些信息內容

包括文章所獲得星數,文章名,以及文章的鏈接。

首先,展示一下成品

 

 

 

 下面展示具體的操作過程:

首先請求該url

import requests
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'

r = requests.get(url)

print("Status Code:" ,r.status_code)輸出

輸出結果為:

 

 說明url請求成功

我們將其json格式化,就獲得了之前提到的巨大的json格式的字典

在根據字典的key值,提取對應所需要的value,並將其存入列表。

調用Pygal模塊,來將數據進行可視化

 

以下是具體的實現代碼:

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'])  #文章名

    if repo_dict['description']:
        plot_dict = {
            'value': repo_dict['stargazers_count'],  #星數
            'label': repo_dict['description'],  #文章描述
        }
        plot_dicts.append(plot_dict)
    else:
        plot_dict = {
            'value': repo_dict['stargazers_count'],
            'label': 'None'
        }
        plot_dicts.append(plot_dict)

#格式設置 my_style = LS('#333366',base_style=LCS)  # 333366灰色 my_config = pygal.Config() my_config.x_label_rotation = 45 my_config.show_legend = False my_config.title_font_size = 24 my_config.label_font_size = 14 my_config.major_label_font_size = 18 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 Project on Github' chart.x_labels = names chart.add('',plot_dicts) chart.render_to_file('python_repos.svg')

 

運行過后,會在同目錄下生成一個svg文件,里面所呈現的數據包括了星數,文章名,文章簡介等。

用瀏覽器可直接打開,便可以看到條狀圖成果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM