2012-04-22 19 views
5
{u'Status': u'OK', u'City': u'Ciri\xe8', u'TimezoneName': '', u'ZipPostalCode': '', u'CountryCode': u'IT', u'Dstoffset': u'0', u'Ip': u'x.x.x.x', u'Longitude': u'7.6', u'CountryName': u'Italy', u'RegionCode': u'12', u'Latitude': u'45.2333', u'Isdst': '', u'Gmtoffset': u'0', u'RegionName': u'Piemonte'} 

これは私のオブジェクトの出力です。私はCityにアクセスしたいが、それはエンコードされている。どのように私はすべてのパラメータを読み、それがPythonでユニコード文字列を変換する

>>> data['City'] 
u'Ciri\xe8' 

>>>data['City'].decode('utf-8') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    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 character u'\xe8' in position 4: ordinal not in range(128) 

私は平文ではないユニコード文字列を望んでデコードすることができます。ありがとうございました!

+0

私はこのコードを使用しています。https://github.com/sonicrules1234/pyipinfodb/blob/master/pyipinfodb.py – dani

+0

"平文"のようなものはありません。 –

+2

何もする必要はありません。それは既にデコードされています... 'print '[' City'] 'を試してみてください – JBernardo

答えて

8

この読み:それからちょうどそれを印刷http://nedbatchelder.com/text/unipain.html

を:

>>> data = {u'City':u'Ciri\xe8'} 
>>> data['City'] 
u'Ciri\xe8' 
>>> print data['City'] 
Ciriè 

あなたはそれを印刷しない場合は、PythonのプリントをUnicodeテキストu''であり、ASCII以外の文字\xe8が含まれていることを示す文字列の安全な表現です。 printは、ターミナルエンコーディングでUnicode文字列をエンコードして非ASCII文字を表示しようとします。文字列は、端末のエンコーディングでサポートされていない文字が含まれている場合、それは失敗することがあります。上記の例で

>>> print u'\xe8' 
è 
>>> print u'\x81' 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "d:\dev\Python27\lib\encodings\cp437.py", line 12, in encode 
    return codecs.charmap_encode(input,errors,encoding_map) 
UnicodeEncodeError: 'charmap' codec can't encode character u'\x81' in position 0: character maps to <undefined> 

を、code page 437は、Unicode文字U + 00E8はなく、U + 0081をサポートしています。

0

平文では、あなたはasciiを意味すると思います。このためには使用することができます。

data['City'].encode('ascii','ignore') 

これはUnicode文字を削除し、

Ciri 

詳細については、このリンクを参照してください返されます:何がしたいことは明確ではありませんhttp://docs.python.org/howto/unicode.html

9

。 '平文' であなたがアクセントを削除する意味場合は、これを試してみてください。

>>> s = u'Ciri\xe8' 
>>> from unicodedata import normalize 
>>> normalize('NFKD', s).encode('ASCII', 'ignore') 
'Cirie' 
関連する問題