python的編碼判斷_unicode_gbk/gb2312_utf8(附函數)


python中, 我們平常使用最多的三種編碼為 gbk/gb2312,  utf8 ,  unicode。 而python中並沒有一個函數來進行 編碼的判斷。今天,主要對這三種編碼進行討論,並給出區分這三種編碼的函數。

我們知道,

      unicode編碼是1位       gbk,gb2312是2位       utf-8是3位

所以,若只有一個漢字,我們可以通過 長度來判斷:

len(u'') == 1 #True
len(u''.encode("gbk"))  == 2  #True
len(u''.encdoe("utf-8")) == 3  #True

但是實際中,往往是一句話,包含好多漢字。於是,我們做如下實驗:

  • 1,u'啊'.encode("gbk")[0].decode("gbk") 將會提示錯誤  UnicodeDecodeError: 'gbk' codec can't decode byte 0xb0 in position 0: incomplete multibyte sequence
  • 2,u'啊'.encode('utf8')[0].decode("utf8") 將會提示錯誤 UnicodeDecodeError: 'utf8' codec can't decode byte 0xe5 in position 0: unexpected end of data
  • 3,u'啊'.encode('gbk')[0].decode('utf8')  將會提示錯誤 UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 0: invalid start byte
  • 4,u'啊'.encode('utf8')[0].decode('gbk')  將會提示錯誤 UnicodeDecodeError: 'gbk' codec can't decode byte 0xe5 in position 0: incomplete multibyte sequence
  • 5,u'啊'.decode('utf8')       將會提示錯誤           UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128)
  • 6,u'啊'.decode('gbk')       將會提示錯誤           UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in position 0: ordinal not in range(128)

由以上可以看出,提示錯誤若出現 ascii,則該句編碼位 ascii 無疑,從2,3可以看出 .decode("utf8")可以區分出不同的編碼: unexpected end of data 表示 該句為 utf8編碼, 而 invalid start byte 則表示 該句為gbk編碼或者gb2312編碼。

綜上,可以編寫如下函數來進行編碼判斷:(python27)

#! -*-encoding:utf8 -*-
def whichEncode(text):
  text0 = text[0]
  try:
    text0.decode('utf8')
  except Exception, e:
    if "unexpected end of data" in str(e):
      return "utf8"
    elif "invalid start byte" in str(e):
      return "gbk_gb2312"
    elif "ascii" in str(e):
      return "Unicode"
  return "utf8"
if __name__ == "__main__":
  print(whichEncode(u"".encode("gbk")))
  print(whichEncode(u"".encode("utf8")))
  print(whichEncode(u""))
  

 在網上看到另一種方法,感覺也不錯,from: https://my.oschina.net/sanpeterguo/blog/209134,,,,from_from:http://my.oschina.net/u/993130/blog/199214

def getCoding(strInput):
    '''
    獲取編碼格式
    '''
    if isinstance(strInput, unicode):
        return "unicode"
    try:
        strInput.decode("utf8")
        return 'utf8'
    except:
        pass
    try:
        strInput.decode("gbk")
        return 'gbk'
    except:
        pass
        
def tran2UTF8(strInput):
    '''
    轉化為utf8格式
    '''
    strCodingFmt = getCoding(strInput)
    if strCodingFmt == "utf8":
        return strInput
    elif strCodingFmt == "unicode":
        return strInput.encode("utf8")
    elif strCodingFmt == "gbk":
        return strInput.decode("gbk").encode("utf8")

def tran2GBK(strInput):
    '''
    轉化為gbk格式
    '''
    strCodingFmt = getCoding(strInput)
    if strCodingFmt == "gbk":
        return strInput
    elif strCodingFmt == "unicode":
        return strInput.encode("gbk")
    elif strCodingFmt == "utf8":
        return strInput.decode("utf8").encode("gbk")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM