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

python的编码和解码

2013-05-06 21:14 169 查看
在python编程的过程中,编码和解码是经常遇见的问题。

常见的编码有unicode,gb2312,gbk,utf-8等等。

在编码和解码的过程过,使用最频繁的函数就是decode()和encode。

其中decode()函数,表示把字符串从原有编码,解码成unicode中间编码。

encode()函数,表示把字符串从unicode中间编码,转换成目标编码。

举例:

lines = open(input_file_name, 'r').readlines()
for line in lines:
line = line.strip()
line = line.decode('gbk')   # 从原有的gbk编码,转换成unicode中间编码
line = line.encode('utf-8') # 从unicode中间编码,转换成UTF-8编码
output_file.write(line + '\n')


在使用decode()或者encode()函数的过程当中,经常会碰到诸如这样的问题:

'gbk' codec can't decode byte 0xc1 in position 8687: incomplete multibyte sequence

表示在编码或者解码的过程当中,碰到无法编解码的字符。

如果你不希望被这样的错误中断程序的运行,可以加上一个忽略这类错误的参数ignore.

line = line.decode('gbk', 'ignore')
line = line.encode('utf-8', 'ignore')


表示忽略掉无法转换的字符。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: