【发布时间】:2021-08-11 02:06:12
【问题描述】:
所以,我有像这样的非二进制字符串,它的编码被破坏了:
函数\xc3\xb3n est\xc3\xa1ndar 日期时间。约会时间。 now() retorna la fecha y hora actual.
这个字符串应该是这样的:
La función estándar 日期时间。约会时间。 now() retorna la fecha y hora actual.
在交互式控制台中,很容易修复:就像这样:
>>> b'La funci\xc3\xb3n est\xc3\xa1ndar datetime. datetime. now() retorna la fecha y hora actual.'.decode('utf-8')
这将输出正确解码的字符串。但是,在我尝试构建的脚本中,这个字符串就像您在第一个示例中看到的一样,但是是 unicode,而不是二进制。
我已经尝试了所有我能想到的技巧(除了硬编码一个等价字典并将它与replace() 一起使用,如果我能帮助它,我宁愿不这样做):我尝试过的最疯狂的事情是:
# Just to clarify the format of the broken strings, I declare this one here
broken_string = 'La funci\\xc3\\xb3n est\\xc3\\xa1ndar datetime. datetime. now() retorna la fecha y hora actual.'
match = re.findall(r'\\x[a-z0-9][a-z0-9]', broken_string)
for e in match:
broken_string = str(broken_string.encode().replace( e.encode(), str(chr(int(e[-2:], 16))).encode() ))
好吧,实际上这个循环最终把字符串弄得更糟了:-$
这个可怕的火车残骸只是我能向你展示的最疯狂的想法。实际上,我已经尝试了很多东西,以至于我都不记得它们了。但你可能会在这里看到我的意图。
实际上很有趣,我似乎无法以一种优雅的方式解决这个问题,而无需硬编码这种风格的字典以在循环中与 str.replace() 一起使用:
dict_for_fix = {
'\\xc3\\xb3' : b'\xc3\xb3'.decode('utf-8'),
# I mean, I would have to brute-force hardcode lots of combinations this way...
}
这让我大吃一惊。没有比这更优雅的解决方案了吗?
【问题讨论】:
-
如果你
print(my_str[8:11])你会得到什么? -
我收到
\xc。这说明了什么? -
做
broken_string.encode('ascii').decode('unicode_escape').encode('latin1').decode('utf8')实际上可能是你想要的。 -
有效!!它确实有效!谢谢...我已经浪费了两三个小时或更长时间试图弄清楚...您确实使我免于遭受更多小时的痛苦。我根本不知道“unicode_escape”的存在。 你可以继续发布它作为答案:-)
-
@metatoaster 我知道你在那里做了什么,这是很多不明显的步骤。绝对值得变成正确的答案。
标签: python python-3.x character-encoding python-3.6