1. ホーム
  2. Python

pygalマッピング "AttributeError: 'NoneType' オブジェクトには 'decode' という属性がありません"

2022-02-20 03:05:15

最近、「<Python Becomes」の17章を読んでいます。入門から実践まで>本 Web Apiの使い方

17.2.3 データからの描画

# coding=utf-8
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# Execute the API call and store the response
URL = 'https://api.github.com/search/repositories?q=language:python&sort=star'
r = requests.get(URL)
print("Status code:", r.status_code)
# Store the API response in a variable
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
# Research information about the repository
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)
# visualize
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の説明)の1つが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