您的位置:首页 > 编程语言 > Python开发

《Python从入门到实践》第17章对GitHub最受欢迎的python仓库排名用pygal可视化(python_repos.py)报错原因及解决

2020-02-02 00:55 881 查看

书中第349页运行python_repos.py报如下错误:

AttributeError: 'NoneType' object has no attribute 'decode'

对仓库们进行id和description打印,查看一下哪里出了问题:

import requests

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

response_dict = r.json()
print("Total repositories:", response_dict['total_count'])

repositories = response_dict['items']
for i in repositories:
print('id:',i['id'],'\nDescription:',i['description'])

程序运行后对仓库的id和description依次进行打印:

可以看到id为3544424的Description有问题,显示报错UnicodeEncodeError.
去API调用(https://api.github.com/search/repositories?q=language:python&sort=stars)看一下这个仓库的描述是这个样子的:

这个httpie的描述有一个🥧就是不能转码的原因。
之前看到别人说的如果Description是空值(None)也会报错,我现在看的这个排名里的仓库恰好没有空值。
解决:
在plot_dict这个字典里,description用str()转换成字符串:

plot_dict = {
'value':i['stargazers_count'],
'label':str(i['description']),
}

然后就可以顺利出图啦!鼠标放到条形时显示的项目描述还是会正常显示🥧的!

小小扩展:
刚刚那个检查的代码遇到第一个不能打印的描述时就停止了,可以用try-except来看看所有不能正常打印的描述:

import requests

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

response_dict = r.json()
print("Total repositories:", response_dict['total_count'])

repositories = response_dict['items']
for i in repositories:
try:
print('id:',i['id'],'\nDescription:',i['description'])
except UnicodeEncodeError:
print('CANNOT PRINT DESCRIPTION')

凡是有不能转码的描述都会打印CANNOT PRINT DESCRIPTION

  • 点赞
  • 收藏
  • 分享
  • 文章举报
Jean_821 发布了12 篇原创文章 · 获赞 0 · 访问量 981 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐