如何将utf8编码转换为字符串?

2024-05-16 23:15:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图对一些推文进行预处理。该文本位于tweepy刮取的csv文件中。我使用的是Jupyter笔记本,假设它存储在变量“p”中,当我使用单元格输出时,文本看起来像这样:

"b'@sarahbea34343 \\xf0\\x9f\\x98\\x94 I\\xe2\\x80\\x99m not going in overly optimistic tbh but hey... https://twitter.com/icxdsfdf'"

相反,如果我用Jupyter打印(p),则输出为:

"b'@sarahbea34343 \xf0\x9f\x98\x94 I\xe2\x80\x99m not going in overly optimistic tbh but hey... https://twitter.com/icxdsfdf'"

我在互联网上查过,这似乎是字节类utf-8编码。 所以我尝试使用“.decode('utf-8')”进行解码,但它给出了一个错误。我发现的问题是,由于它存储在csv文件中,utf-8编码被存储为一个字符串,因此整个tweet就是一个字符串。这意味着即使反斜杠也被编码为字符串。我似乎不知道如何转换它,以便删除这些表情符号和其他字符的utf编码

我尝试了多种方法,再次返回相同的字符串,例如:

p.encode('ascii','ignore').decode('ascii')

or p.encode('latin-1').decode('utf-8').encode('ascii', 'ignore')


Tags: 文件csv字符串文本编码asciijupyterutf
1条回答
网友
1楼 · 发布于 2024-05-16 23:15:49

如果文本确实是这样存储的(因此您正在以文本模式“r”读取文件),则可以执行以下操作:

# Strip leading b and inner quotes
s = "b'@sarahbea34343 \xf0\x9f\x98\x94 I\xe2\x80\x99m not going in overly optimistic tbh but hey... https://twitter.com/icxdsfdf'"[2:-1]

# Encode as latin-1 to get bytes, decode from unicode-escape to unescape 
# the byte expressions (\\xhh -> \xhh), encode as latin-1 again to get 
# bytes again, then finally decode as UTF-8.

new_s = encode('latin-1').decode('unicode-escape').encode('latin-1').decode('utf-8')
print(new_s)
@sarahbea34343 😔 I’m not going in overly optimistic tbh but hey... https://twitter.com/icxdsfdf

相关问题 更多 >