【问题标题】:'UCS-2' codec can't encode characters in position 1050-1050“UCS-2”编解码器无法对位置 1050-1050 中的字符进行编码
【发布时间】:2015-12-03 05:48:29
【问题描述】:

当我运行我的 Python 代码时,我收到以下错误:

  File "E:\python343\crawler.py", line 31, in <module>
    print (x1)
  File "E:\python343\lib\idlelib\PyShell.py", line 1347, in write
    return self.shell.write(s, self.tags)
UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 1050-1050: Non-BMP character not supported in Tk

这是我的代码:

x = g.request('search', {'q' : 'TaylorSwift', 'type' : 'page', 'limit' : 100})['data'][0]['id']

# GET ALL STATUS POST ON PARTICULAR PAGE(X=PAGE ID)
for x1 in g.get_connections(x, 'feed')['data']:
    print (x1)
    for x2 in x1:
        print (x2)
        if(x2[1]=='status'):
            x2['message']

我该如何解决这个问题?

【问题讨论】:

  • 如果您需要查看非 bmp Unicode 字符;您可以在可以显示它们的环境中交互地运行 python,例如在 ConEmu 控制台或 Web 浏览器中。试试ipython notebook

标签: python unicode encoding ucs2


【解决方案1】:

您的数据包含Basic Multilingual Plane 之外的字符。比如 Emoji 就在 BMP 之外,IDLE 使用的窗口系统 Tk 不能处理这样的字符。

您可以使用 translation table 将 BMP 之外的所有内容映射到 replacement character

import sys
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
print(x.translate(non_bmp_map))

non_bmp_map 将 BMP 之外的所有代码点(高于 0xFFFF 的任何代码点,一直到 highest Unicode codepoint your Python version can handle)映射到 U+FFFD REPLACEMENT CHARACTER

>>> print('This works outside IDLE! \U0001F44D')
This works outside IDLE! ?
>>> print('This works in IDLE too! \U0001F44D'.translate(non_bmp_map))
This works in IDLE too! �

【讨论】:

  • 谢谢,但添加这些后,显示新错误:print (x1.translate(non_bmp_map)) AttributeError: 'dict' object has no attribute 'translate',怎么办?
  • @Andi:x1 不是字符串,而是字典。在这种情况下,您可以使用str(x1).translate(non_bmp_map)
【解决方案2】:

这些都不适合我,但以下内容对我有用。这假设 public_tweets 是从 tweepy api.search 中提取的

for tweet in public_tweets:
    print (tweet.text)
    u=tweet.text
    u=u.encode('unicode-escape').decode('utf-8')

【讨论】:

    【解决方案3】:

    这个 unicode 问题已经在 python 3.6 和更早的版本中出现,要解决它只需将 python 升级为 python 3.8 并使用您的代码。这个错误不会出现。

    【讨论】:

    • 我很高兴支持您的回答,因为 1) 我觉得它非常有用,2) 我是第一个在 stackoverflow 上支持您的人。
    猜你喜欢
    • 2018-01-24
    • 2018-11-12
    • 2018-12-12
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2017-11-06
    相关资源
    最近更新 更多