Python转码问题的解决方法
时间:2023-06-30 07:48:52
比如,若要将某个String对象s从gbk内码转换为UTF-8,可以如下操作
s.decode('gbk').encode('utf-8′)
可是,在实际开发中,我发现,这种办法经常会出现异常:
UnicodeDecodeError: ‘gbk' codec can't decode bytes in position 30664-30665: illegal multibyte sequence
这 是因为遇到了非法字符——尤其是在某些用C/C++编写的程序中,全角空格往往有多种不同的实现方式,比如\xa3\xa0,或者\xa4\x57,这些 字符,看起来都是全角空格,但它们并不是“合法”的全角空格(真正的全角空格是\xa1\xa1),因此在转码的过程中出现了异常。
这样的问题很让人头疼,因为只要字符串中出现了一个非法字符,整个字符串——有时候,就是整篇文章——就都无法转码。
解决办法:
s.decode('gbk', ‘ignore').encode('utf-8′)
因为decode的函数原型是decode([encoding], [errors='strict']),可以用第二个参数控制错误处理的策略,默认的参数就是strict,代表遇到非法字符时抛出异常;
如果设置为ignore,则会忽略非法字符;
如果设置为replace,则会用?取代非法字符;
如果设置为xmlcharrefreplace,则使用XML的字符引用。
python文档
decode( [encoding[, errors]])
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is 'strict', meaning that encoding errors raise UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error, see section 4.8.1.
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django学习教程之静态文件的调用详解
Python+DeOldify实现老照片上色功能
![](https://img.aspxhome.com/file/2023/3/131403_0s.jpg)
jquery插件bootstrapValidator数据验证详解
![](https://img.aspxhome.com/file/2023/3/136953_0s.jpg)
JavaScript数组去重的几种方法
如何正确处理数据库中的Null
python去除字符串中的空格、特殊字符和指定字符的三种方法
![](https://img.aspxhome.com/file/2023/4/106984_0s.jpg)
Python控制键盘鼠标pynput的详细用法
JS获取checkbox的个数简单实例
浅谈MySQL排序原理与案例分析
![](https://img.aspxhome.com/file/2023/4/89924_0s.png)
解决windows上安装tensorflow时报错,“DLL load failed: 找不到指定的模块”的问题
Python算法之栈(stack)的实现
Python中常见的加密解密算法总结
numpy自动生成数组详解
Python爬虫实例——scrapy框架爬取拉勾网招聘信息
![](https://img.aspxhome.com/file/2023/2/131212_0s.png)
vantUI 获得piker选中值的自定义ID操作
![](https://img.aspxhome.com/file/2023/5/139685_0s.jpg)
关于Dreamweaver乱码问题的解决方案
MySQL 字符串截取相关函数小结
MySQL基于GTID主从搭建
Windows下Python2与Python3两个版本共存的方法详解
![](https://img.aspxhome.com/file/2023/8/111888_0s.jpg)