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

Moh*_*ani 6 python python-3.x pandas

当我尝试使用:

df[df.columns.difference(['pos', 'neu', 'neg', 'new_description'])].to_csv('sentiment_data.csv')
Run Code Online (Sandbox Code Playgroud)

我收到错误:

UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 388: surrogates not allowed
Run Code Online (Sandbox Code Playgroud)

我不明白这个错误意味着什么以及我如何修复这个错误并将我的数据导出到 csv/excel。我已经提到了这个问题,但我不太明白,它没有回答如何用熊猫来做到这一点。

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

当我尝试导出到 excel 时,我得到了一个不同的错误位置:

df[df.columns.difference(['pos', 'neu', 'neg', 'new_description'])].to_excel('sentiment_data_new.xlsx')
Run Code Online (Sandbox Code Playgroud)

导出到excel时出错:

UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 261: surrogates not allowed
Run Code Online (Sandbox Code Playgroud)

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

其他重复的问题没有回答如何使用 Pandas DataFrame 来避免这个错误。

Boa*_*les 16

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

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

"\ud83d\ude04".encode('utf-16','surrogatepass').decode('utf-16')
Run Code Online (Sandbox Code Playgroud)

这将为您提供代码点\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 '\U0001f604' in position 0: Non-BMP character not supported in Tk.

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

print ('\U0001f604')
Run Code Online (Sandbox Code Playgroud)

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

print ("\ud83d\ude04".encode('utf-16','surrogatepass').decode('utf-16'))
Run Code Online (Sandbox Code Playgroud)

并且两者都会打印

您仍然不能做的是按原样打印 UTF-16 代理对:如果您尝试,print ("\ud83d\ude04")您将获得相同的\u转义符。