【Pyhton】pygal数据可视化报错:“AttributeError: 'NoneType' object has no attribute 'decode'”

错误来源:《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
    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

来看看生成的图形效果:

【Pyhton】pygal数据可视化报错:“AttributeError: 'NoneType' object has no attribute 'decode'”_第1张图片

你可能感兴趣的:(python,python,pygal,可视化,数据分析)