錯誤來源:《Python程式設計:從入門到實踐》一書第17章第2節第3小節!
原書代碼:
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'
result = requests.get(url)
print("status code:",result.status_code)
#将API響應存儲在一個變量中
response_dict = result.json()
print("Total reposeitories:",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'])
plot_dict = {
'value':repo_dict['stargazers_count'],
'label':repo_dict['description'],
}
plot_dicts.append(plot_dict)
#配置可視化圖形
my_style = LS('#8F4586',base_style=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 = True #是否顯示水準線
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('pyhton_repos.svg')
代碼執行後報錯:
status code: 200
Total reposeitories: 2989171
Repositories returned: 30
Traceback (most recent call last):
File "D:/PythonWorkstation/learning_path/day06/API/test.py", line 46, in <module>
chart.render_to_file('pyhton_repos.svg')
File "D:\python3\Anaconda3\lib\site-packages\pygal\graph\public.py", line 114, in render_to_file
f.write(self.render(is_unicode=True, **kwargs))
***
AttributeError: 'NoneType' object has no attribute 'decode'
問題猜想:
可能是repo_dict的‘description’的參數為none,是以我們加入if--else來判斷一下。代碼如下:
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)
再次運作:
status code: 200
Total reposeitories: 2989190
Repositories returned: 30
Process finished with exit code 0
來看看生成的圖形效果: