如何解码三字节编码的字符串?

问题描述 投票:0回答:1

我一直在使用 pandas 数据帧,其中一列是字节编码的。我用 .decode('utf-8') 对它进行了解码一次,它适用于数据的主要部分,但有一些字符串恰好被编码了不止一次。例如: b'b'b\'[{"charcName":"\\u0420\\u0438\\u0441\\u0443\\u043d\\u043e\\u043a","charcValues":["\\u043c\ \u0438\u043b\u0438\u0442\u0430\u0440\u0438\u043a\u0430\u043c\u0443\u0444\u043b\u044f\u0436"]}]\' ''

我尝试对其进行解码(并进行编码,以防止错误“str”对象没有属性“decode”),但它似乎不起作用。我怎样才能完全解码这些字符串? utf-8 和 unicode_escape 解码应按什么顺序应用?

python utf-8 decoding
1个回答
0
投票

原始字符串无效,因此我去掉了字节装饰并专注于列表:

import ast
import json

s = '''[{"charcName":"\\\\u0420\\\\u0438\\\\u0441\\\\u0443\\\\u043d\\\\u043e\\\\u043a","charcValues":["\\\\u043c\\\\u0438\\\\u043b\\\\u0438\\\\u0442\\\\u0430\\\\u0440\\\\u0438 \\\\u043a\\\\u0430\\\\u043c\\\\u0443\\\\u0444\\\\u043b\\\\u044f\\\\u0436"]}]'''
s = ast.literal_eval(s)
s = s[0]
s['charcName'] = s['charcName'].encode().decode('unicode_escape')
s['charcValues'][0] = s['charcValues'][0].encode().decode('unicode_escape')

print('# Original object:')
print(s)
print('\n# Properly encoded in JSON (tell the hacks of the original data how to do it):')
print(json.dumps(s))
print('\n# Or this, but make sure to write this to a UTF-8-encoded database or file.')
print(json.dumps(s, ensure_ascii=False))

输出:

# Original object:
{'charcName': 'Рисунок', 'charcValues': ['милитари камуфляж']}

# Properly encoded in JSON (tell the hacks of the original data how to do it):
{"charcName": "\u0420\u0438\u0441\u0443\u043d\u043e\u043a", "charcValues": ["\u043c\u0438\u043b\u0438\u0442\u0430\u0440\u0438 \u043a\u0430\u043c\u0443\u0444\u043b\u044f\u0436"]}

# Or this, but make sure to write this to a UTF-8-encoded database or file.
{"charcName": "Рисунок", "charcValues": ["милитари камуфляж"]}
© www.soinside.com 2019 - 2024. All rights reserved.