一個簡單的例子unicode的變量:Python的解碼與非ASCII字符或不
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import traceback
e_u = u'abc'
c_u = u'中國'
print sys.getdefaultencoding()
try:
print e_u.decode('utf-8')
print c_u.decode('utf-8')
except Exception as e:
print traceback.format_exc()
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
try:
print e_u.decode('utf-8')
print c_u.decode('utf-8')
except Exception as e:
print traceback.format_exc()
輸出:
ascii
abc
Traceback (most recent call last):
File "test_codec.py", line 15, in <module>
print c_u.decode('utf-8')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
utf-8
abc
中國
一些問題困擾了我幾天,當我想徹底瞭解編解碼器在Python中,我想確保我認爲是正確的:
根據
ascii
de故障編碼,u'abc'.decode('utf-8')
沒有錯誤,但是u'中國'.decode('utf-8')
有錯誤。我覺得做
u'中國'.decode('utf-8')
,Python的檢查,發現當u'中國'
是unicode的,所以儘量做到u'中國'.encode(sys.getdefaultencoding())
,這樣會導致問題,而例外的是UnicodeEncodeError
,不是錯誤的時候解碼。但
u'abc'
與'abc'
(< 128)的代碼點相同,所以沒有錯誤。在Python 2.x中,python內部存儲變量值如何?如果字符串< 128中的所有字符視爲
ascii
,如果> 128,則視爲utf-8
?In [4]: chardet.detect('abc') Out[4]: {'confidence': 1.0, 'encoding': 'ascii'} In [5]: chardet.detect('abc中國') Out[5]: {'confidence': 0.7525, 'encoding': 'utf-8'} In [6]: chardet.detect('中國') Out[6]: {'confidence': 0.7525, 'encoding': 'utf-8'}
我知道應該使用'encode',我的問題是,爲什麼在u'abc」使用解碼都沒有問題,而且我認爲是正確的? – 2015-01-21 09:22:09
請參閱我的答案的第二部分,其中描述了unicode.decode()在內部的行爲。這應該清楚爲什麼'u'abc'.decode()'意外地工作。 – vog 2015-01-21 09:38:33
你說的第2部分,我認爲錯誤:'從unicode字符串的任何隱式轉換爲字節字符串,總是使用ASCII字符set.'。請參閱我問的示例代碼,如果將默認編碼更改爲utf-8,則可以。 – 2015-01-21 14:12:33