'NoneType'对象没有属性'decode'

时间:2019-07-04 14:59:23

标签: python visualization pygal

我练习编写一些代码来从GitHub获取Python的顶级存储库,这是我看到的错误:

enter image description here

这是导致上述错误的代码:

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')

请您帮我一下。谢谢

2 个答案:

答案 0 :(得分:2)

我查看了您的代码。看起来有些链接没有标签(因此它们的类型为None)See here_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')

也许您找到了一种更好的方法来映射列表,但这绝对可行。

答案 1 :(得分:1)

在期望字符串的某处似乎有一个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'],
}