gpt4 book ai didi

python - 统一码编码错误 : 'utf-8' codec can't encode character '\ud83d' in position 388: surrogates not allowed

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:52 50 4
gpt4 key购买 nike

当我尝试使用时:

df[df.columns.difference(['pos', 'neu', 'neg', 'new_description'])].to_csv('sentiment_data.csv')

我得到错误:

UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 388: surrogates not allowed

我不明白此错误的含义以及如何修复此错误并将我的数据导出到 csv/excel。我已经提到这个 question但我不太了解,也没有回答如何用 Pandas 做到这一点。

位置388是什么意思? '\ud83d'这个字符是什么?

当我尝试导出到 excel 时出现不同的错误位置:

df[df.columns.difference(['pos', 'neu', 'neg', 'new_description'])].to_excel('sentiment_data_new.xlsx')

导出到 excel 时出错:

UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 261: surrogates not allowed

为什么相同编码的位置不同?

The other duplicate questions don't answer how to escape this error with pandas DataFrame.

最佳答案

Unicode 中的表情符号位于基本多语言 Pane 之外,这意味着它们的代码点不适合 16 位。代理对是一种使这些字形在 UTF-16 中直接表示为一对 16 位代码点的方法。

您可以强制将代理项对解析为 BMP 之外的相应代码点,如下所示:

"\ud83d\ude04".encode('utf-16','surrogatepass').decode('utf-16')

这将为您提供代码点 \U0001f604。请注意如何使用超过 4 个十六进制数字来表示。

但这个解决方案可能只能帮您到此为止。

很多软件(包括 pygame 和旧版本的 IDLE、PowerShell 和 Windows 命令提示符)只支持 BMP,因为它并不真正使用 UTF-16,而是它的前身UCS-2,本质上是 UTF-16,但不支持 BMP 之外的代码点。

最初发布此答案时,在 IDLE 3.7 及之前的版本中,print ('\U0001f604') 只会引发 UnicodeEncodeError: 'UCS-2' codec can't encode character位置 0 中的“\U0001f604”:Tk 不支持非 BMP 字符

Python 3.8 最终修复了这个问题,并且这些修复被移植到 Python 3.7 的后续版本,所以现在在 IDLE 中,您可以提供 17 位代码点:

print ('\U0001f604')

或将 UTF-16 代理对转码为相同的代码点:

print ("\ud83d\ude04".encode('utf-16','surrogatepass').decode('utf-16'))

两者都会打印😄

你仍然不能做的是按原样打印 UTF-16 代理对:如果你尝试 print ("\ud83d\ude04") 你会得到相同的 \u 转义回来。

关于python - 统一码编码错误 : 'utf-8' codec can't encode character '\ud83d' in position 388: surrogates not allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54536539/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com