在python中,unicode是內存編碼集,一般我們將數據存儲到文件時,需要將數據先編碼為其他編碼集,比如utf-8、gbk等。
讀取數據的時候再通過同樣的編碼集進行解碼即可。
#python3
>>> s = '中國'
>>> a = s.encode()
>>> a
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> b = a.decode()
>>> b
'中國'
但是其實還有一種unicode-escape編碼集,他是將unicode內存編碼值直接存儲:
#python3
>>> s = '中國'
>>> b = s.encode('unicode-escape')
>>> b
b'\\u4e2d\\u56fd'
>>> c = b.decode('unicode-escape')
>>> c
'中國'
拓展:還有一種string-escape編碼集,在2中可以對字節流用string-escape進行編碼
#python2
>>> s = '中國'
>>> a = s.decode('gbk')
>>> print a
中國
>>> b = s.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\python\python2.7\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd6 in position 0: invalid c
ontinuation byte
>>> c = s.decode('string-escape')
>>> print c
中國
chardet.detect()
使用chardet.detect()進行編碼集檢測時很多時候並不准確,比如中文過少時會識別成IBM855編碼集:
#python3
>>> s = '中國'
>>> c = s.encode('gbk')
>>> chardet.detect(c)
{'encoding': 'IBM855', 'confidence': 0.7679697235616183, 'language': 'Russian'}
注:855 OEM 西里爾語 IBM855。
中文比較多時,還是准確的:
>>> s = '中國范文芳威風威風'
>>> c = s.encode('gbk')
>>> chardet.detect(c)
{'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}