python 中的编码问题总结

来源:互联网 发布:拆弹部队知乎 编辑:程序博客网 时间:2024/06/11 16:26
一、首先,请选择python3.x最新版本。 
  
因为最新版本的编码问题相对于之前的2.0版本要好不少。 
  
二、在编写程序代码时,习惯性地在代码开始处加上下面的语句。 

默认地,python的.py文件以标准的7位ASCII码存储,而不是unicode格式的,然而如果有的时候用户需要在.py文件中包含很多的unicode字符,例如.py文件中需要包含中文的字符串,这时可以在.py文件的第一行或第二行增加encoding注释来将.py文件指定为unicode格式。

#!/usr/bin/env python   #设置Python解释器
# -*- coding: UTF-8 -*-   #声明文件编码为utf-8

s = "中国" # String in quotes is directly encoded in UTF-8. 
  
三、编写完代码,把代码存储成.py文件时确保文件编码与声明一致。 
  
当你编写完代码,把代码存储成.py文件时,一定要将文件编码设为与开头的文件编码声明一致的编码(如:声明为# -*- coding: UTF-8 -*-,则可以通过使用notepad++等软件指定.py文件为utf-8编码)
#获取文件的默认编码
import sys
print(sys.getdefaultencoding()) 
#设置python文件的编码
#encoding=uft-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
  
四、python3.2版本中对文件的读写操作都要指明编码。 
  
参考代码如下: 
f =  open("1.txt","r",encoding="utf-8")
当然也可以使用codecs包进行文件的读取,在使用open()函数时指定编码的类型:
import codecs
f=codecs.open('123.txt','r+',encoding='utf-8) 
  
五、python3.2版本中对于要读取的文件,如果文件的编码并不知道,可以先使用chardet(第三方库,需要下载)来进行判断,然后再根据判断所得的文件编码类型,指定文件的编码类型来进行文件的读取操作。 
  
参考代码如下: 
file =  open(fileName, "rb")#要有"rb",如果没有这个的话,默认使用gbk读文件。           
buf = file.read()   
result = chardet.detect(buf)   
file = open(fileName,"r",encoding=result["encoding"])   
content = file.readlines() 
 
使用中,chardet.detect()返回字典,其中confidence是检测精确度,encoding是编码形式 
  
(1)网页编码判断: 
  
>>> import urllib 
>>> rawdata = urllib.urlopen('http://www.google.cn/').read() 
>>> import chardet 
>>> chardet.detect(rawdata) 
  
检测的结果是:{'confidence': 0.98999999999999999, 'encoding': 'GB2312'} 
  
(2)文件编码判断 
  
import chardet 
tt=open('c:\\111.txt','rb') 
ff=tt.readline()#这里试着换成read(5)也可以,但是换成readlines()后报错 
enc=chardet.detect(ff) 
print enc['encoding'] 
tt.close() 
另外为了提高探测速度,可使用如下方式
detector = UniversalDetector() 
for line in f.readlines(): 
      detector.feed(line) 
      if detector.done: 
          break 
detector.close() 
detector.result  
(3)字符串编码的判断
    isinstance(s,str) 用来判断是否为一般字符串
    isinstance(s,unicode)  用来判断是否为unicode
或者:
    if type(str).__name__!="unicode":
         str=unicode(str,"utf-8")
    else:
          pass.
Python的encode和decode的用法:
无论是在python2.0还是在python3.0中,在做编码转换时,都通常以unicode做为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。
一、Python2.0
          decode                           encode
str--------------------->unicode----------------->str
如:  str=u"中文"   #指定str为unicode类型对象
      uni=str.encode('gb2312')      #unicode编码转换为gb2312编码
二、Python3.0
        在新版的python3.0中,取消了unicode类型,代替它的是使用unicode字符的字符串类型str:
         decode                         encode
bytes------------>str(unicode)----->bytes
注:代码中的字符串的默认编码与代码文件本身的编码是一致的,如:s=“中文",若在utf8的文件中,该字符串就是utf8编码,此时要进行编码转换,都需要先用decode方法将其转换为unicode编码,在使用encode方法将其转换成其他编码。在没有指定特定的编码方式时,使用系统默认编码。
s=u"中文"
则该字符串的编码已被指定为unicode了,即python的内部编码,而与文件本身的编码无关。此时,只需要使用encode方法就可以将其转换成指定编码即可。如果字符串已经是unicode时,再进行解码会出错,这是就需要判断其编码方式是否为unicode:
   isinstance(s,unicode)
用非unicode编码形式的str来encode也会报错。
unicode(str,gb2312)与str.decode(gb2312)一样,都将gb2312编码的str转为unicode编码。

python2和python3中str的比较:
初学Python的简单文件操作编码问题 - changfengmingzhi - 长风明志的博客
python3中的str的转化函数:
初学Python的简单文件操作编码问题 - changfengmingzhi - 长风明志的博客
 
 可能需要str的转化的情况:
初学Python的简单文件操作编码问题 - changfengmingzhi - 长风明志的博客
 可能需要str的转化的情况:
初学Python的简单文件操作编码问题 - changfengmingzhi - 长风明志的博客
0 0