我有一个 csv 文件 ( see here ),其中包含来自 Facebook 公共(public)页面帖子的元数据。我需要解码所有内容,如:\xc3\xa9
和 \xf0\x9f\x91\xa9\xf0\x9f\x8f\xbb\xe2\x80\x8d\xf0\x9f\x92\xbc
元数据“发布消息”是:
"b'Bom dia, genteee! Me disseram que esse emoji \xc3\xa9 a minha cara: \xf0\x9f\x91\xa9\xf0\x9f\x8f\xbb\xe2\x80\x8d\xf0\x9f\x92\xbc\nO que voc\xc3\xaas acham?'"
它的类型是str对象。
我需要将其转换为:
Bom dia, genteee! Me disseram que esse emoji é a minha cara: 👩🏻💼 O que vocês acham?
我该怎么做?我需要转换所有 csv。
编辑 1:我试过了
My_string = post_message.split("b'")[1].split("'")[0]
My_string.encode().decode('unicode_escape')
但是结果和我预想的不一样:
Bom dia, genteee! Me disseram que esse emoji é a minha cara: ð©ð»âð¼ O que vocês acham?
解决方案:
正如@Ben 所指出的,我的数据是一个包含字节的字符串对象,而不是字节对象。所以使用@ShadowRanger 解决方案(see his answer here) .我做了:
My_string = post_message[2:len(post_message)-1] #to remove "b'" from begining and "'" from end
My_string = My_string.encode('utf-8').decode('unicode_escape').encode('latin-1').decode('utf-8')
结果:
Bom dia, genteee! Me disseram que esse emoji é a minha cara: 👩🏻💼 O que vocês acham?
最佳答案
我注意到您发布的字符串看起来像“b'...'”,在带有 b 前缀的单引号字符串周围用双引号引起来。这看起来像是一个包含字节串文本表示的字符串,而不是作为文本打印的字节串。
例如:
>>> text = 'föő'
>>> text
'föő'
>>> bytestring = text.encode()
>>> bytestring
b'f\xc3\xb6\xc5\x91'
>>> str(bytestring)
"b'f\\xc3\\xb6\\xc5\\x91'"
它表明您在某个时候有一个字节串,并在其上调用 str
(或类似的东西)以将其转换为文本字符串。这为您提供了字节串的文本表示,而不是字节串编码的文本。
但是,如果该理论完全正确,您将使用双反斜杠,如您在上面的示例中所见。所以它并不完全适合,如果数据与您在 OP 中显示的完全一样。
但是,看起来代码在某些时候仍然有字节并且错误地将它们转换为文本。我会强烈建议您通过找到发生问题的位置并修复它来解决此问题,而不是在事后尝试更正此数据。
关于python - 如何解码 python 中的反斜杠转义字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885694/