pygal制图“AttributeError: 'NoneType' object has no attribute 'decode'”

最近在看<Python变成:从入门到实践>书中的17章 使用Web Api

17.2.3 根据数据绘图

# coding=utf-8
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=star'
r = requests.get(URL)
print("Status code:", r.status_code)
# 将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
# 研究有关仓库的信息
repo_dicts = response_dict['items']
print "Number of items:",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'],
                   'xlink':repo_dict['html_url']
                   }
        plot_dicts.append(plot_dict)
    else:
        plot_dict={'value':repo_dict['stargazers_count'],
                   'label':'ABC',
                   'xlink':repo_dict['html_url']}
        plot_dicts.append(plot_dict)
# 可视化
my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names

chart.add('', plot_dicts)
print plot_dicts
chart.render_to_file('python_repos.svg')

上面的代码和书中有些不同,主要是

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'],
                   'xlink':repo_dict['html_url']
                   }
        plot_dicts.append(plot_dict)
    else:
        plot_dict={'value':repo_dict['stargazers_count'],
                   'label':'ABC',
                   'xlink':repo_dict['html_url']}
        plot_dicts.append(plot_dict)

为什么加上这段?

按书上的写法,出现如下报错

Traceback (most recent call last):
  File "C:/Users/vivi01.zhu/PycharmProjects/untitled2/python_repos.py", line 32, in <module>
    chart.render_to_file('python_repos.svg')
  File "C:\Python27\lib\site-packages\pygal\graph\public.py", line 114, in render_to_file
    f.write(self.render(is_unicode=True, **kwargs))
  File "C:\Python27\lib\site-packages\pygal\graph\public.py", line 52, in render
    self.setup(**kwargs)
  File "C:\Python27\lib\site-packages\pygal\graph\base.py", line 217, in setup
    self._draw()
  File "C:\Python27\lib\site-packages\pygal\graph\graph.py", line 933, in _draw
    self._plot()
  File "C:\Python27\lib\site-packages\pygal\graph\bar.py", line 146, in _plot
    self.bar(serie)
  File "C:\Python27\lib\site-packages\pygal\graph\bar.py", line 116, in bar
    metadata)
  File "C:\Python27\lib\site-packages\pygal\util.py", line 233, in decorate
    metadata['label'])
  File "C:\Python27\lib\site-packages\pygal\_compat.py", line 61, in to_unicode
    return string.decode('utf-8')
AttributeError: 'NoneType' object has no attribute 'decode'

需要显示在图上的plot_dicts可以打印出来,且正常

猜测是因为其中有个参数(repo_dict的description)为none,无属性,对此参数加上是否为none的if--else判断,运行通过,bingo~

('Status code:', 200)
('Total repositories:', 1923446)
Number of items: 30
[{'xlink': u'https://github.com/vinta/awesome-python', 'value': 38175, 'label': u'A curated list of awesome Python frameworks, libraries, software and resources'}.................{'xlink': u'https://github.com/drduh/macOS-Security-and-Privacy-Guide', 'value': 11824, 'label': u'A practical guide to securing macOS.'}]

Process finished with exit code 0


猜你喜欢

转载自blog.csdn.net/waiwai3/article/details/77847783
今日推荐