《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
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- python编程从入门到实践——数据可视化之使用api(第17章)
- 基于pygal对GitHub最受欢迎的python项目做可视化分析
- 已解决:为什么移动的外星人只有一列了?【python入门到实践13章】
- python编程从入门到实践——数据可视化之下载数据(第16章)
- python调用matlab,并解决安装pywin32报错原因
- 使用pygal可视化GitHub上星数最多的仓库
- python subprocess命令行调用py文件 报错EOFError: EOF when reading a line (已解决)
- python编程从入门到实践——数据可视化之生成数据
- 用python爬github上星级排名前列的项目报错AttributeError: 'NoneType' object has no attribute 'decode'
- GitHub入门与实践(四)——Git的基本操作从初始化仓库到确认提交是否成功
- (待翻译)github入门之遇到SSH Permission Denied问题的原因和解决
- python_慕课\django入门与实践\6-1 Models.py
- [置顶] python爬虫实践——零基础快速入门(六)解决动态页面爬取问题
- python_慕课\django入门与实践\2-1 课前准备.py
- GitHub入门与实践(2)掌握Git 4、推送至远程仓库
- GitHub入门与实践(2)掌握Git 5、从远程仓库获取
- Python编程从入门到实践 393页,394页和396页 urls.py以及views.py 有误修改
- python 进行caffe 数据可视化的 “No to_python (by-value)” 问题解决
- Python编程:从入门到实践(课后习题6)
- Github过万标星,Python新人100天学习计划,从入门到工作!