【问题标题】:Convert a list of string to unicode characters in python在python中将字符串列表转换为unicode字符
【发布时间】:2012-03-22 01:20:15
【问题描述】:

我的 python 代码使用 facebook API 来请求用户的信息。并且名称可以包含 Unicode 字符:

# -*- 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 字符时出现此错误:

文件“C:\Python27\lib\encodings\cp437.py”,第 12 行,在编码中 返回 codecs.charmap_encode(输入,错误,encoding_map) UnicodeEncodeError:“charmap”编解码器无法在位置编码字符 u'\u0169' 7:字符映射到

如果你能帮我解决这个问题,请提前感谢! :)

【问题讨论】:

    标签: python facebook unicode facebook-fql


    【解决方案1】:

    快速而肮脏的答案是使用somestring.encode('ascii', 'ignore') 来处理意外字符。

    我怀疑你的代码有更深层次的问题。如果您要打印真正的 unicode 字符串,则不必先对它们进行编码(否则,它们的含义将在 print 到达它们之前丢失):

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

    另外,print '%s: %s'.encode('ascii') % (attr, info[attr]) 行正在编码模板任何字符串替换发生之前。这可能不是您想要的。

    【讨论】:

    • @IgnacioVazquez-Abrams "ũ" 出现在 OP 的错误消息中。他的快速解决方法是忽略它。
    【解决方案2】:

    问题是您的控制台不支持您收到的一个或多个字符。您可以执行 chcp 65001 以使控制台支持 UTF-8(另外,您不必手动编码),但这可能会对从同一控制台运行的其他程序产生不利影响。

    【讨论】:

      【解决方案3】:

      最简单的解决方案是使用支持 UTF-8 的 IDE,例如带有 pywin32 扩展的 Pythonwin。将您的字符串保留为 Unicode,然后打印它们,它们将在 UTF-8 终端上正确显示(当然,只要字体支持这些字符)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-18
        • 2014-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多