python:正確的對未知編碼的字串進行預處理-Unicode-UTF8-gbk
阿新 • • 發佈:2019-02-02
由於計算機只能識別二進位制資料,所以指望程式自動的猜出字串是如何編碼的很難。
而現實中,我們經常得到編碼方式未知的字串,我們總是希望能將這些字串先統一預轉換為unicode編碼,在處理以後再根據需要編碼到需要的格式
為了判斷原始字串的編碼格式,可以採用chardet模組
我編寫了下面的一個函式,用以從檔案中讀取資訊,並統一轉換為unicode格式返回,同時返回的還有資料的原始編碼格式(如’utf-8‘)
def readFile2UnicodeBuf(filename): readstring=None oldCodingType=None try: with open(filename, 'rb') as pf: readstring=pf.read() if isinstance(readstring, unicode): oldCodingType='unicode' else: oldCodingType=chardet.detect(readstring)['encoding'] readstring=readstring.decode(oldCodingType) except: print 'ERROR: read file fail:'+filename return None,None return readstring,oldCodingType