![](/img/trans.png)
[英]AttributeError: “NoneType” object has no attribute 'decode'
[英]'NoneType' object has no attribute 'decode'
我練習編寫一些代碼來從GitHub獲取Python的頂級存儲庫,這是我看到的錯誤:
這是導致上述錯誤的代碼:
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
path = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(path)
response_dict = r.json()
# Explore information about the repositories.
repo_dicts = response_dict['items']
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'],
'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)
my_style = LS('#333366', base_style=LCS)
# Make visualization.
my_config = pygal.Config()
chart = pygal.Bar(my_config, style=my_style)
my_style = LS('#333366', base_style=LCS)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')
你能幫我這個忙嗎? 謝謝
我看着你的代碼。 看起來有些鏈接沒有標簽(因此它們的類型為None)。 請參見此處 。 _compat.py
然后嘗試對None-Type調用方法decode ("utf-8")
,這將導致相應的崩潰。
我建議plot_dicts中所有沒有標簽的條目都用空字符串標記,如下面的代碼所示。 下面的代碼對我有用。
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
path = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(path)
response_dict = r.json()
# Explore information about the repositories.
repo_dicts = response_dict['items']
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'],
'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)
my_style = LS('#333366', base_style=LCS)
# Make visualization.
my_config = pygal.Config()
chart = pygal.Bar(my_config, style=my_style)
my_style = LS('#333366', base_style=LCS)
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names
# preprocess labels here
def f(e):
if e['label'] is None:
e['label'] = ""
return e
plot_dicts = list(map(f, plot_dicts))
chart.add('', plot_dicts)
chart.render_to_file('python_repos.svg')
也許您找到了映射列表的更好方法,但這絕對可行。
似乎在期望字符串的某處有一個None
值,並且回溯似乎表明它是label
值。
嘗試更改此:
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'],
'xlink': repo_dict['html_url'],
}
對此:
plot_dict = {
'value': repo_dict['stargazers_count'],
'label': repo_dict['description'] or "",
'xlink': repo_dict['html_url'],
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.