2016-01-12 48 views
0

我想問你的幫助。我不得不解碼unicode十進制字符,但我不解碼只有clasisc字母,我正在解碼特殊字符,如:؋,лв和更多¥並且它不起作用 - 它說:'charmap'編解碼器無法編碼字符。你可以幫我嗎?Python - unichr() - 'charmap'編解碼器不能編碼字符

我有從本頁面貨幣的所有符號的工作:http://www.xe.com/symbols.php,謝謝。

編輯: 比如我需要從十進制數1547符號得到「؋」。

回答

1

它有助於提供如下示例。這說明了操作環境(操作系統和Python版本):

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> print(unichr(1547)) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Python27\encodings\cp437.py", line 12, in encode 
    return codecs.charmap_encode(input,errors,encoding_map) 
UnicodeEncodeError: 'charmap' codec can't encode character u'\u060b' in position 0: character maps to <undefined> 

問題不在於轉換,而在於打印。在上述情況下,Windows控制檯使用cp437編碼,並且不支持要打印的字符。

轉換工作正常,c包含Unicode字符,這是AFGHANI SIGN

>>> c = unichr(1547) 
>>> c 
u'\u060b' 
>>> import unicodedata as ud 
>>> ud.name(c) 
'AFGHANI SIGN' 

如果你想讓它正確打印,一個方法是使用一個IDE PythonWin從支持UTF-8編碼輸出pywin32擴展:

PythonWin 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32. 
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. 
>>> unichr(1547) 
u'\u060b' 
>>> print(unichr(1547)) 
؋ 

另一種是寫輸出到一個UTF-8編碼的文件,並在記事本中打開結果:

with io.open('out.txt','w',encoding='utf8') as f: 
    f.write(unichr(1547)+unichr(402)+unichr(165)) 

輸出文件:

؋ƒ¥ 
相關問題