好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

python编码总结(编码类型、格式、转码)

本文详细总结了python编码。分享给大家供大家参考,具体如下:

tmp_str = 'tmp_str'
print tmp_str.__class__   #<type 'str'>
print type(tmp_str)    #<type 'str'>
print type(tmp_str).__name__ #str
tmp_str = u'tmp_str'
print tmp_str.__class__   #<type 'unicode'>
print type(tmp_str)    #<type 'unicode'>
print type(tmp_str).__name__ #unicode 
import urllib2
import chardet
res = urllib2.urlopen('http://HdhCmsTestgxlcms测试数据')
res_cont = res.read()
res.close()
print chardet.detect(res_cont) #{'confidence': 0.99, 'encoding': 'utf-8'} 
import urllib2
from chardet.universaldetector import UniversalDetector
res = urllib2.urlopen('http://HdhCmsTestgxlcms测试数据')
detector = UniversalDetector()
for line in res.readlines():
 #detect untill reach threshold
 detector.feed(line)
 if detector.done:
  break
detector.close()
res.close()
print detector.result
#{'confidence': 0.99, 'encoding': 'utf-8'} 
#将任意字符串转换为unicode
def to_unicode(s, encoding):
 if isinstance(s, unicode):
  return s
 else:
  return unicode(s, encoding) 
import locale
#get coding type
print locale.getdefaultlocale() #('zh_CN', 'cp936')
#set coding type
locale.setlocale(locale.LC_ALL, locale='zh_CN.GB2312')
print locale.getlocale() #('zh_CN', 'gb2312') 
import sys
reload(sys)
print sys.getdefaultencoding() #ascii
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding() #utf-8 
stra = u"中"
print stra.encode("gbk") 

按上面说的stra是unicode形式,直接encode称gbk编码应该没问题啊?但是实际执行时会报错“UnicodeEncodeError: 'gbk' codec can't encode character u'\xd6' in position 0: illegal multibyte sequence”。

原因在于:python解释器在导入python代码文件并执行时,会先查看文件头有没有编码声明(例如#coding:gbk等)。如果发现声明,会将文件中的字符串都先解释成unicode的形式(这里先用默认编码gbk(cp936)将stra解码成unicode编码'd6d0'后保存),之后执行stra.encode('gbk')时,由于stra已经是unicode编码且'd6d0'在gbk的编码范围内,所以编码不会出现错误;如果文件头没有编码声明,则不会进行上述过程中的解码操作(这里就直接使用stra的unicode编码'd6'),之后执行stra.encode('gbk')时,由于'd6'不在gbk的编码范围所以报错。

(2)为避免这种类型的错误,最好在代码文件头上声明编码,或者麻烦点每次使用setdefaultencoding()。

(3)总的来说就是unicode是python解释器的内码,所有代码文件在导入并执行时,python解释器会先将字符串使用你指定的编码形式解码成unicode,然后再进行各种操作。所以不管是对字符串的操作,还是正则表达式,还是读写文件等等最好都通过unicode来进行。

【python中其他编码】

文件系统的编码:sys.getfilesystemencoding()
终端的输入编码:sys.stdin.encoding
终端的 输出编码:sys.stdout.encoding

更多python编码总结(编码类型、格式、转码)相关文章请关注PHP中文网!

查看更多关于python编码总结(编码类型、格式、转码)的详细内容...

  阅读:48次