Python ';UCS-2和x27;编解码器可以';在1050-1050位置对字符进行编码

Python ';UCS-2和x27;编解码器可以';在1050-1050位置对字符进行编码,python,unicode,encoding,ucs2,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 encod

运行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

如何修复此问题?

您的数据包含的字符超出了。例如,表情符号在BMP之外,IDLE使用的窗口系统Tk无法处理此类字符

您可以使用将BMP之外的所有内容映射到:

non_bmp_map
将bmp之外的所有代码点(任何高于0xFFFF的代码点,一直到)映射到:

>>>打印('这在空闲外部工作!\U0001F44D')

这在外面工作,空闲 这些对我来说都不管用,但以下几点确实管用。这假设公共推文是从tweepy api.search中提取的


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

谢谢,但添加这些之后,会显示新的错误:print(x1.translate(non_bmp_map))AttributeError:'dict'对象没有属性'translate',那么怎么做呢?@Andi:
x1
不是字符串,而是字典。在这种情况下,您可以执行
str(x1).translate(非bmp\u映射)
;您可以在能够显示python的环境中以交互方式运行python,例如在ConEmu控制台或web浏览器中。试试看。我很高兴对你的答案投赞成票,因为1)我觉得它非常有用,2)我是第一个向你投赞成票欢迎你加入stackoverflow的人。
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']
import sys
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
print(x.translate(non_bmp_map))
>>> print('This works outside IDLE! \U0001F44D')
This works outside IDLE! None of these worked for me but the following does.  This assumes that public_tweets was pulled from tweepy api.search

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