python - 'UCS- 2' codec can' t 在位置 1050-1050 编码字符

标签 python unicode encoding ucs2

当我运行我的 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']

我该如何解决这个问题?

最佳答案

您的数据包含 Basic Multilingual Plane 之外的字符.例如,表情符号在 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! �

关于python - 'UCS- 2' codec can' t 在位置 1050-1050 编码字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32442608/

相关文章:

Python - 增加特定控制台输出的大小

html - 我如何处理 CSS 中的异常字符?

python - 使用python向翻译器发送utf-8请求

java - spring mvc 路径变量编码

python - 如何使用 spaCy 从数据框列创建标记化单词列表?

python - python模块导入-相对路径问题

python - 如何在 Numpy 中取 long 的对数

python - 从 Matplotlib 集合中检索标记

video - 我的视频中编码了多少关键帧? ffmpeg 是使用的编码器

python - 如何在Python中解码日元符号?