[Python Crash Course] API

import requests                                 # API

import pygal                                    # visualization

from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS


# make an API call and store the response #
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)             # status_code: whether the request is successful(200)
#    store response
response_dict = r.json()                         # json(): convert to Python dictionary
# print(response_dict.keys())
print("Total repositories:", response_dict['total_count'])


# Explore information about repositories #
repo_dicts = response_dict['items']               # items: a list of dictionaries(individual Python repository)
# print("Repositories returned:", len(repo_dicts))
#    Examine the first repository #
# repo_dict = repo_dicts[0]
# print("\nKeys:", len(repo_dict))
# for key in sorted(repo_dict.keys()):              # the information of each project
#     print(key)


# Summarize the top repositories #
names, stars, plot_dicts = [], [], []
for repo_dict in repo_dicts:
    # print('\nName:', 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'])
    names.append(repo_dict['name'])
    stars.append(repo_dict['stargazers_count'])
    # plot data #
    plot_dict = {
        'value': repo_dict['stargazers_count'],
        'label': str(repo_dict['description']),
        'xlink': repo_dict['html_url']
    }
    plot_dicts.append(plot_dict)


# visualization #
my_style = LS('#336699', base_style=LCS)
# chart = pygal.Bar(style=my_style, x_label_rotation=45, show_lengend=False)  # 45 degrees; hide the legend

#    refine charts #
my_config = pygal.Config()                      # a configuration object
my_config.x_label_rotation = 45
my_config.show_legend = False
#           size #
my_config.title_front_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15                   # shorten names to 15 words // truncate:截断的
my_config.show_y_guides = False                 # hide the horizontal lines
my_config.width = 1000

chart = pygal.Bar(my_config, style=my_style)
chart.title = 'Most-Started Python Projects on Github'
chart.x_labels = names

# chart.add('', stars)                          # the string will appears at each strip as a title
chart.add('', plot_dicts)                       # all information in the dictionary will appear at the strips
chart.render_to_file('repos_PlotData.svg')

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页