编码方法encoding(

描述

  encode() 方法以指定的编码格式编码字符串,默认编码为 'utf-8'。将字符串由string类型变成bytes类型。

  对应的解码方法:bytes decode()  方法。

语法

  str.encode([encoding='utf-8'][,errors='strict'])

  • str是表示需要编码的字符串,并且是个string类型。
  • encoding -- 可选参数,要使用的编码方案,默认编码为 'utf-8'。
  • errors -- 可选参数,设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

返回值

  该方法返回编码后的字符串,它是一个 bytes 对象,这个字节对象是用于下面的解码用的。

官方文档解释:

  str.encode(encoding="utf-8"errors="strict")

  Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors   raise a UnicodeError. Other possible values are 'ignore''replace''xmlcharrefreplace''backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list   of possible encodings, see section Standard Encodings.

  Changed in version 3.1: Support for keyword arguments added.

------------------------------------------------------------------------------------------------------------------------------------------------

解码方法decode()

  decode() 方法以 encoding 指定的编码格式来解码字符串。默认编码规则是encoding=‘utf-8’

语法

  bytes.decode(encoding='UTF-8',errors='strict')

参数

  bytes是由编码方法encoding()编码转换过后得到的字符串的字节表示值。

  encoding -- 解码时要使用的编码方案,如"UTF-8"。

  errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

返回值:

  该方法返回解码后的字符串。

官方文档解释

  bytes.decode(encoding="utf-8"errors="strict")bytearray.decode(encoding="utf-8"errors="strict")

  Return a string decoded from the given bytes. Default encoding is 'utf-8'errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise            a UnicodeError. Other possible values are 'ignore''replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard       Encodings.

  Note

  Passing the encoding argument to str allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object.

  Changed in version 3.1: Added support for keyword arguments.

其实编码解码的关系就是如下:

str->bytes:encode编码

bytes->str:decode解码  
字符串通过编码成为字节码,字节码通过解码成为字符串。可以这样解释,编码就是将字符串转换成字节码,涉及到字符串的内部表示。解码就是将字节码转换为字符串,将比特位显示成字符。

例如:

 >>> text = '我是文本'
>>> text
'我是文本'
>>> print(text)
我是文本
>>> bytesText = text.encode()
>>> bytesText
b'\xe6\x88\x91\xe6\x98\xaf\xe6\x96\x87\xe6\x9c\xac'
>>> print(bytesText)
b'\xe6\x88\x91\xe6\x98\xaf\xe6\x96\x87\xe6\x9c\xac'
>>> type(text)
<class 'str'>
>>> type(bytesText)
<class 'bytes'>
>>> textDecode = bytesText.decode()
>>> textDecode
'我是文本'
>>> print(textDecode)
我是文本

例2

 >>>text='我好吗'
>>>byteText=text.encode('gbk')
>>>byteText
b'\xce\xd2\xba\xc3\xc2\xf0'
>>>strText=byteText.decode('gbk')
>>>strText
'我好吗'
>>>byteText.decode('utf-8')
Traceback (most recent call last):
File "G:\softs\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-11-f0ef1443f388>", line 1, in <module>
byteText.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 0: invalid continuation byte

上面的第8行出现了错误,是由于文本text='我好吗',是按照‘gbk’进行编码的,而在解码时是按照‘utf-8’的编码规则进行的解码,所以会导致解码失败,即‘utf-8’不能解码‘gbk’编码规则的字节。用相对应的解码编码规则来对字符进行处理。下面给出了几条处理这种错误的方法供参考。

出现如下错误时

UnicodeDecodeError: 'gbk' codec can't decode byte 0xab in position 11126: illegal multibyte sequence

使用python的时候经常会遇到文本的编码与解码问题,其中很常见的一种解码错误如题目所示,下面介绍该错误的解决方法,将‘gbk’换成‘utf-8’也适用。 
(1)、首先在打开文本的时候,设置其编码格式,如:open(‘1.txt’,encoding=’gbk’); 
(2)、若(1)不能解决,可能是文本中出现的一些特殊符号超出了gbk的编码范围,可以选择编码范围更广的‘gb18030’,如:open(‘1.txt’,encoding=’gb18030’); 
(3)、若(2)仍不能解决,说明文中出现了连‘gb18030’也无法编码的字符,可以使用‘ignore’属性进行忽略,如:open(‘1.txt’,encoding=’gb18030’,errors=‘ignore’);

(4)、还有一种常见解决方法为open(‘1.txt’).read().decode(‘gb18030’,’ignore’)

对于机器学习实战第四章朴素贝叶斯一张代码实现出现的解码错误就用了上面的方法(4)解决了

 def spamTest():
docList=[];classList=[];fillText=[]
for i in range(1,26):
wordList=textParse(open('D:/machinelearning data/machinelearninginaction/Ch04/email/spam/%d.txt' % i,encoding='utf-8',errors='ignore').read())
# print('%d word:'%i)
docList.append(wordList)
fillText.extend(wordList)
classList.append(1)
wordList = textParse(open('D:/machinelearning data/machinelearninginaction/Ch04/email/ham/%d.txt' % i,encoding='utf-8',errors='ignore').read())
docList.append(wordList)
fillText.extend(wordList)
classList.append(0)

原文上面代码出现错误是因为在解析ham文件夹文件23.txt时出现解码错误,才导致整个文件运行不了,我们将文件打开的编码方式统一换成'utf-8',并且忽略掉出现的错误便可以正常运行了

参考资料:

1,https://www.cnblogs.com/tingyugetc/p/5727383.html

2,https://blog.csdn.net/shijing_0214/article/details/51971734

Python中解码decode()与编码encode()与错误处理UnicodeDecodeError: 'gbk' codec can't decode byte 0xab的更多相关文章

  1. Anaconda中启动Python时的错误:UnicodeDecodeError: 'gbk' codec can't decode byte 0xaf in position 553

    今天,在Anaconda prompt启动python遇到了如下错误: UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xaf in positi ...

  2. Python转码问题的解决方法:UnicodeDecodeError:‘gbk' codec can't decode bytes in position

    在开发过程中遇到了错误:UnicodeDecodeError: ‘gbk' codec can't decode bytes in position 678-679...这是因为遇到了非法字符, 解决 ...

  3. Python读取文件时出现UnicodeDecodeError 'gbk' codec can't decode byte 0x80 in position x

    Python在读取文件时 with open('article.txt') as f: # 打开新的文本 text_new = f.read() # 读取文本数据出现错误: UnicodeDecode ...

  4. Python读取文件时出现UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position xx: 解决方案

    Python在读取文件时 with open('article.txt') as f: # 打开新的文本 text_new = f.read() # 读取文本数据 出现错误: UnicodeDecod ...

  5. python3 读取dbf文件报错 UnicodeDecodeError: 'gbk' codec can't decode

    在读取dbf文件时由于编码问题报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xb5 in position 49: incomplete ...

  6. python编码问题:UnicodeDecodeError: 'gbk' codec can't decode

    在获取yaml文件数据时,提示:UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 2: illegal multib ...

  7. python print 打印的数据包含中文,打印报错UnicodeDecodeError: 'gbk' codec can't decode bytes in position 459-460: illegal multibyte sequence解决办法

    python 2.7 print 的数据中若包括中文,打印则会报错UnicodeDecodeError: 'gbk' codec can't decode bytes in position 459- ...

  8. python 读取文件时报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 205: illegal multib

    python 读取文件时报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 205: illegal multib ...

  9. 中文数据解码报错 UnicodeDecodeError: 'gbk' codec can't decode bytes in position 2-3: illegal multibyte sequence

    UnicodeDecodeError: 'gbk' codec can't decode bytes in position 2-3: illegal multibyte sequence 失败原因: ...

随机推荐

  1. O​r​a​c​l​e​ ​D​a​t​a​b​a​s​e​ ​e​x​p​r​e​s​s​ ​1​1​g​ ​第​ ​2​ ​版​安​装和配置

    官方Oracle Database 快捷版 11g 第 2 版的下载地址: http://www.oracle.com/technetwork/cn/products/express-edition/ ...

  2. ETA6093 或 ETA9741 ETA9742 的 TYPE-C 的资料收集

    ETA6093 或 ETA9741 ETA9742 的 TYPE-C 的资料收集 因为项目使用. 这个 IC 好玩,但是还是有一些需要注意的. 对我有用的信息. http://www.great-et ...

  3. odoo 数据库选择的随笔

    odoo 数据库选择的随笔 看到有人讨论 odoo 是否可以使用 SQL Server(MS SQL). 原来 odoo 使用的是 PostgreSQL,PostgreSQL 是很先进的关系性数据库, ...

  4. npm查看全局安装过的包

    在使用node的时候,用npm安装了很多软件,过一段时间没有使用就会忘记,怎么查看自己全局安装过的包,用命令 npm list -g --depth 0 在百度里搜不到结果的,我在google里老外的 ...

  5. struts2学习(2)struts2核心知识

    一.Struts2 get/set 自动获取/设置数据 根据上一章.中的源码继续. HelloWorldAction.java中private String name,自动获取/设置name: pac ...

  6. C++ 函数特性_参数默认值

    函数参数默认值写法 有默认参数值的参数必须在参数表的最右边 ,) // 这是正确的写法 , int k) // 这是错误写法 先声明,后定义 在写函数时要先在代码前面声明,然后再去定义. 函数默认参数 ...

  7. PHP CRC16 校验码的算法怎么使用

    PHP CRC16 校验码的算法如何使用最近用到CRC16, 我现在就是要把 010301180001 算出CRC16的校验码,通过其他工具,可以得到 校验码是 05F1 最后完整的代码就是 0103 ...

  8. Lucene根据字段进行自定义搜索扩展

    最近需要对公司的产品搜索功能做一步改动,搜索到的结果首先按照是否有库存进行排序,然后再按照销量.由于库存量也是一个整数,如果直接按照库存量进行倒序排序的话,是不符合要求的,Lucene也没有支持我们这 ...

  9. Linux知识温习

    进程间通信(IPC)介绍 mmap - 用户空间与内核空间 linux 进程地址空间的一步步探究 mmap 还是 shmget ? linux C/C++服务器后台开发面试题总结 Trie树详解及其应 ...

  10. Android开发入门——ImageView的设置

    在熟悉了android后,总是对系统自带的ic_launcher这个小机器人不太喜欢,想换成自己喜欢的图片,接下来就介绍两种方法来实现把imageView的ic_launcher换成自己喜欢的图片. ...