2016-11-04 4 views
0

Pythonスクリプトiso-8859-1になっutf-8文字列をエンコードしようとすると失敗します。文字の文字セットを知るには?

>>> 'à'.encode('iso-8859-1') 
UnicodeEncodeError: 'latin-1' codec can't encode character '\u0300' in position 1: ordinal not in range(256) 

ウィッヒ文字セットを知る方法は、その文字のですか?場合UTF-8でエンコードして:

>>> 'à'.encode('utf-8') 
b'a\xcc\x80' 

a次いで\xcc\x80。私はをhttp://www.utf8-chartable.de/unicode-utf8-table.pl?start=768&names=-&utf8=string-literal utf8テーブルに入れることができます。

しかし、それはutf-8ですか? utf-8の場合'à'.encode('utf-8')はこの文字列をiso-8859-1にエンコードできません。

答えて

0

'à'の文字はどこから来ているのかは不明です。実際には、combining character sequenceであり、normalizeにする必要があります。次のPythonスクリプトは、自己説明し、ご質問を解決するためにunicodedata moduleを使用しています。

import sys, platform 
print (sys.stdout.encoding, platform.python_version()) 
print() 

import unicodedata 
agraveChar='à'  # copied from your post 
agraveDeco='à'  # typed as Alt+0224 (Windows, us keyboard) 

# print Unicode names 
print ('agraveChar', agraveChar, agraveChar.encode('utf-8')) 
for ins in range(0, len(agraveChar)): 
    print (agraveChar[ins], unicodedata.name(agraveChar[ins], '???')) 

print ('agraveDeco', agraveDeco, agraveDeco.encode('utf-8')) 
for ins in range(0, len(agraveDeco)): 
    print (agraveDeco[ins], unicodedata.name(agraveDeco[ins], '???')) 


print ('decomposition(agraveChar)', unicodedata.decomposition(agraveChar)) 
print ('\nagraveDeco normalized:\n') 
print ("NFC to utf-8", unicodedata.normalize("NFC" , agraveDeco).encode('utf-8')) 
print ("NFC to latin", unicodedata.normalize("NFC" , agraveDeco).encode('iso-8859-1')) 
print ("NFKC to utf-8", unicodedata.normalize("NFKC", agraveDeco).encode('utf-8')) 
print ("NFKC to latin", unicodedata.normalize("NFKC", agraveDeco).encode('iso-8859-1')) 

出力

==> D:\test\Python\40422359.py 
UTF-8 3.5.1 

agraveChar à b'\xc3\xa0' 

à LATIN SMALL LETTER A WITH GRAVE 

agraveDeco à b'a\xcc\x80' 

a LATIN SMALL LETTER A 
̀ COMBINING GRAVE ACCENT 

decomposition(agraveChar) 0061 0300 

agraveDeco normalized: 

NFC to utf-8 b'\xc3\xa0' 
NFC to latin b'\xe0' 
NFKC to utf-8 b'\xc3\xa0' 
NFKC to latin b'\xe0' 

==>