首页 > 解决方案 > AttributeError:“NoneType”对象没有属性“startswith”

问题描述

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS


url = "https://api.github.com/search/repositories? 
q=language:python&sort=stars"
r = requests.get(url)

response_dict = r.json()

names,stars = [],[]
for repo in repo_dicts:
    names.append(repo["name"])
    stars.append(repo["stargazers_count"])

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(" ", stars)
chart.render_to_file("repo_visual.svg")

运行此代码时,我得到一个 AttributeError。我正在尝试使用 pygal 模块将星星最多的 python 项目绘制到条形图上。该任务来自 Eric Matthes 的 Python 速成课程。我正在与他的代码交叉检查我的代码,但我似乎找不到任何问题

痕迹:

Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/generatingdata/python_repos.py", line 
51, in <module>
chart.render_to_file("x.svg")

任何帮助是极大的赞赏。

标签: pythonpygal

解决方案


@SagarJhamb 您的代码有两个错误
1.repo_dicts 未初始化
2.定义 my_style= LS("333366", base_style=LCS) 值应以#333366开头,以了解有关使用 pygal 的自定义样式的更多信息,您可以查看 [pygal 文档][1][1]: http: //www.pygal.org/en/stable/documentation/parametric_styles.html

import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS


url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)

response_dict = r.json()
# initialise response dict
repo_dict=response_dict['items']

names,stars = [],[]
for repo in repo_dict:
   names.append(repo["name"])
   stars.append(repo["stargazers_count"])
# #333366 remove your error of NoneType object has no attribute startswith
#It is rightformat of using custom style with pygal
#It should starts with #
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("stars", stars)
chart.render_to_file("repo_visual.svg")

推荐阅读