2012-03-04 29 views
0

私のpythonコードはFacebookのAPIを使ってユーザーの情報を要求しています。そして名前は、Unicode文字を含めることができますuはそれを修正するために私を助け場合は、事前にPythonで文字列のリストをUnicode文字に変換する

File "C:\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'\u0169' in position 7: character maps to

ありがとう:

# -*- coding: utf-8 -*- 
from facebook import Facebook 

def desktop_app(): 
# Get api_key and secret_key from a file 
    facebook = Facebook('x', 'xx') 
    facebook.auth.createToken() 
# Show login window 
    facebook.login() 
# Login to the window, then press enter 
    print 'After logging in, press enter...' 
    raw_input() 
    facebook.auth.getSession() 
    info = facebook.users.getInfo([facebook.uid], [u'name', 'birthday', 'affiliations', 'sex'])[0] 
    for attr in info: 
     print '%s: %s'.encode('ascii') % (attr, info[attr]) 
    friends = facebook.friends.get() 
    friends = facebook.users.getInfo(friends[0:5], [u'name', 'birthday', 'relationship_status']) 
    for friend in friends: 
     if 'birthday' in friend: 
      print friend['name'].encode('utf8'), 'has a birthday on', friend['birthday'], 'and is', friend['relationship_status'] 
     else: 
      print friend['name'].encode('utf8'), 'has no birthday and is', friend['relationship_status'] 
    arefriends = facebook.friends.areFriends([friends[0]['uid']], [friends[1]['uid']]) 

if __name__ == "__main__": 
    desktop_app() 

私はFacebookの名にUnicode文字が含まれているこのエラーを得ました! :)

答えて

0

素早く汚れた答えは、予期しない文字を処理するためにsomestring.encode('ascii', 'ignore')を使用することです。

私はコードに深刻な問題があると思っています。あなたが本当のUnicode文字列を印刷している場合、あなたは彼らが最初に(プリントがそれらに到達する前にそれ以外の場合は、その意味が失われます)をエンコードする必要はありません。

>>> print u'ba\u0169er'  # no encode or decode is needed to print 
baũer 

また、ラインprint '%s: %s'.encode('ascii') % (attr, info[attr])は、テンプレートをエンコードしているの前に文字列の置換が行われています。それはおそらくあなたが意図したものではありません。

+0

CP437には「÷」はありません。 –

+0

@ IgnacioVazquez-Abrams OPのエラーメッセージに「÷」が含まれていました。彼のクイックフィックスはそれを無視することです。 –

0

問題は、お使いのコンソールが受け取っている1つ以上の文字をサポートしていないことです。 chcp 65001を実行すると、コンソールをUTF-8に対応させることができます(また、サイドボーナスとして、手動でエンコードする必要はありません)が、これは同じコンソールから実行される他のプログラムに悪影響を及ぼします。

0

最も簡単な解決策は、PythonwinのようなUTF-8をサポートするIDEを使用して、pywin32という拡張子が付いたものを使用することです。あなたの文字列をUnicodeのままにして、それらを印刷するだけで、UTF-8端末に正しく表示されます(フォントが文字をサポートしている限り)。

関連する問題