Python 报编码错误 UnicodeDecodeError 解决办法

  • 错误:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 894: invalid start byte
  • 指向位置:

  • 缘由:
data = open(filepath, 'rt', encoding='utf-8')
  •  解决办法:读取文件时加error属性
data = open(filepath, 'rt', encoding='utf-8',errors='replace')

 主要缘由:所读取的文件中有乱码,可能是从网页爬取,而造成的乱码字符html

过程:java

  • 开始觉得是编码问题,定位到编码问题,实际上是方向错误。

对于编码问题的解释太多了:python

参考:http://pycoders-weekly-chinese.readthedocs.io/en/latest/issue5/unipain.html通俗的方式说明编码问题的由来和多种解决方式segmentfault

参考:http://www.tuicool.com/articles/6RNv22y只是解决问题型网络

python2中解决方法  参考:http://www.cnblogs.com/zhaoyl/p/3770340.htmlapp

在前面加上如下代码便可函数

import sys 
reload(sys) # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法,咱们须要从新载入 
sys.setdefaultencoding('utf-8')

而在Python3中:若是在控制台中运行,就遇到了以下的UnicodeEncodeError:测试

1.缘由 #参考了http://www.tuicool.com/articles/nEjiEvui

首先,代码中的html.text会自动将获取的内容解析为unicode  (与html.content不一样。二者区别就是html.content的类型是bytes,而html.text类型是str,bytes经过解码(decode)能够获得st r,str经过编码(encode)获得bytes)    html.text这种字符串若是要输出应当用utf-8来编码。而cmd中,(对于多数中国人所用的是中文的系统)默认字符编码是gbkthis

从而致使此种现象:python要将utf-8编码的字符串,在gbk的cmd的中打印出来。因而出现了编码错误

2.解决方法  原文中在贴了含有真正解决方法的网页的网址,

http://www.crifan.com/summary_python_2_x_common_string_encode_decode_error_reason_and_solution/ 

我最终办法就是使用Pycharm这个IDE来运行查看结果,中文部分就能正常显示了。

至于如何在cmd上解决print的问题我仍然不知道如何解决。

写入文件时引起的UnicodeEncodeError:

参考:https://segmentfault.com/a/1190000004269037

在测试过程当中屡次出如今写入文件时报告错误“UnicodeEncodeError: 'ascii' codec can't encode character '\u56de' in position 0: ordinal not in range(128)”,这是因为咱们在抓取网页的时候采用的是UTF-8编码,而存储时没有指定编码,在存储到文件的过程当中就会报错。

解决办法为:在读取文件时加入指定UTF-8编码的选项

f = open('content.txt','a',encoding='UTF-8')

另外须要注意的是使用requests获取到网页以后一样要指定编码

html = requests.get(url)
html = re.sub(r'charset=(/w*)', 'charset=UTF-8', html.text)

另外:关于编码问题

参考:如下网址(几乎包含了能遇到的问题,做者善于总结,并一一讲述问题和解决思路)

http://www.crifan.com/summary_python_2_x_common_string_encode_decode_error_reason_and_solution/(找我本身的笔记本)

总结 2017.05.10:

1. 若是遇到编码问题,首先,是否添加encoding属性;其次,“文件编码”与“读取编码”是否一致;最后,是否须要进行专门的编码转换。

2. 就读取文件自己来讲,可进行模式设置,即回归官网

open(file, mode='r', buffering=-1, encoding=None, errors=None, 
newline=None, closefd=True, opener=None)
  •  
    Character Meaning
    'r' open for reading (default)
    'w' open for writing, truncating the file first
    'x' open for exclusive creation, failing if the file already exists
    'a' open for writing, appending to the end of the file if it exists
    'b' binary mode
    't' text mode (default)
    '+' open a disk file for updating (reading and writing)
    'U' universal newlines mode (deprecated)
  • Error Handlers¶ 主要涉及如下三种方法 固然还有其余,须要的时候去看

  • Value Meaning
    'strict' Raise UnicodeError (or a subclass); this is the default. Implemented instrict_errors().
    'ignore' Ignore the malformed data and continue without further notice. Implemented inignore_errors().

    The following error handlers are only applicable to text encodings:

    Value Meaning
    'replace' Replace with a suitable replacement marker; Python will use the official U+FFFDREPLACEMENT CHARACTER for the built-in codecs on decoding, and ‘?’ on encoding. Implemented in replace_errors().

3. 着手解决文本自己的问题,不要让其出现乱码。如原文原本自网络爬虫(致使编码问题)。 

请尊重劳动成果:http://www.javashuo.com/article/p-gdgqqxul-ep.html

相关文章
相关标签/搜索