pygal製圖“AttributeError: ‘NoneType’ object has no attribute ‘decode’《Python編程:從入門到實踐》
最近在刷《Python編程:從入門到實踐》一書 webAPI 部分使用github接口繪製柱狀圖
遇到此報錯 通過覈對書中代碼 發現並無錯誤
pygal製圖“AttributeError: 'NoneType' object has no attribute 'decode'
通過分析是 接口中 description
爲空原因 ps 原來大神代碼也有不健壯的時候啊
完整代碼:
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 執行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('總數', response_dict['total_count'])
# 探索倉庫有關信息
repo_dicts = response_dict['items']
print('倉庫數量', len(repo_dicts))
# 研究第一個倉庫
repo_dict = repo_dicts[0]
names, plot_dicts = [], []
print("\n最受歡迎的python倉庫:")
for repo_dict in repo_dicts:
# print('\n項目名稱:', repo_dict['name'])
# print('登錄名:', repo_dict['owner']['login'])
# print('Stars:', repo_dict['stargazers_count'])
# print('地址:', repo_dict['html_url'])
# print('創建時間:', repo_dict['created_at'])
# print('更新時間:', repo_dict['updated_at'])
# print('倉庫描述:', repo_dict['description'])
names.append(repo_dict['name'])
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'] if repo_dict['description'] else ' ',
# 添加可單擊的鏈接
'xlink': repo_dict['html_url']
}
plot_dicts.append(plot_dict)
# 可視化
my_style = LS('#333366', base_stayle=LCS)
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 = 'github-python倉庫star統計'
chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')
修改部分
就是這裏 'label': repo_dict['description'] if repo_dict['description'] else ' ',
做個默認值就好了
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'] if repo_dict['description'] else ' ',
# 添加可單擊的鏈接
'xlink': repo_dict['html_url']
}
plot_dicts.append(plot_dict)