【转】python中文decode和encode转码

来源:互联网 发布:电路图设计软件 编辑:程序博客网 时间:2024/06/05 14:20

字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。
encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。

因此,转码的时候一定要先搞明白,字符串str是什么编码,然后decode成unicode,然后再encode成其他编码

一、代码中字符串的默认编码与代码文件本身的编码一致
如果是在utf8的文件中,该字符串就是utf8编码,如果是在gb2312的文件中,则其编码为gb2312。

测试:

我的eclipse里面代码为utf-8编码的。然后我这样写代码
s="你好"s=s.decode('gb2312').encode('utf-8')print s
报错:
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 2-3: illegal multibyte sequence
原因:因为我的文件为UTF-8编码的。所以你想用gb2312将其转成unicode是不可能的。
所以正确的写法应当是:
s="你好"print ss=s.decode('utf-8').encode('utf-8') 要用UTF-8来做编码print s
如果发现打印出来的是乱码控制台是GB2312的编码!

二、如何获得系统的默认编码
#!/usr/bin/env python#coding=utf-8import sysprint sys.getdefaultencoding()
该段程序在英文WindowsXP上输出为:ascii 。我发现我的linux上面也是ascii编码。所以我想打印出来看到的乱码是正常的。因为我其实是utf-8编码的。

在某些IDE中,字符串的输出总是出现乱码,甚至错误,其实是由于IDE的结果输出控制台自身不能显示字符串的编码,而不是代码本身的问题。

1、读文件命令肯定是:
myfile = codecs.open("c.html","r","utf-8")  因为我用gb2312来读的话报错

心得:检查一个字符串是什么编码只需要看一下decode 如果用gb2312来decode没报错的话就表示是gb2312如果用utf-8来decode没有报错的话就表示是utf-8

现在遇到一个问题就是
请看:
myfile = codecs.open("c.html","r","utf-8") str = myfile.read()                                content = str.replace("\n"," ")   content = content.encode('utf-8')print content

没有报错

再看:

myfile = codecs.open("c.html","r","utf-8") str = myfile.read()                                 #显示中文content = str.replace("\n"," ")   content = content.encode('gb2312')                 用gb2312print content
报错:UnicodeEncodeError: 'gb2312' codec can't encode character u'\u2014' in position 12628
再看:
myfile = codecs.open("d.html","r","utf-8") str = myfile.read()                                 #显示中文content = str.replace("\n"," ")   content = content.encode('gb2312')                 用gb2312print content

没问题

myfile = codecs.open("d.html","r","utf-8") str = myfile.read()                                 #显示中文content = str.replace("\n"," ")   content = content.encode('utf-8')                 print content
也没问题
结论:我想是c.html页面里面 存在某些 特殊字符 只支持utf-8编码。而不支持gb2312的编码!而d.html没有这种特殊字符。这也就解释了为什么有的文件并没有发生我们想像中的问题!

三、正则表达式的内容和匹配的内容必须要统一编码
#统一编码myfile = codecs.open("right.html","r")  #不需要设置其编码的!str = myfile.read()                      content = str.replace("\n"," ")content = content.decode('utf-8','ignore')   #使用utf-8解码成unicode格式regex3 = regex3.decode('utf-8','ignore')    #正则也统一使用utf-8解码成unicode格式regex = re.compile(regex3)print regex.findall(content)

原创粉丝点击