我正在创建一个程序,它从API中获取数据并将其存储在我自己的数据库中。问题是某些叮咬有一些引号应该是的字符代码。经过进一步检查,它似乎是引号的十六进制代码,但它是奇迹般地双重逃脱,让我和我的所有解码器混淆。我相信字符串以ascii形式出现,我对其他字符没有任何其他问题。
我知道我可以简单地用特定的字符替换特定的字符代码,但我需要在将来捕获这样的东西。如果它是十六进制,我需要梳理十六进制代码的字符串并在程序上替换它们。
我试过了
clean_val = unicodedata.normalize('NFKD', val).encode('latin1').decode('utf8')
我对整个事情感到非常困惑
response = session.get(url)
if response.status_code == requests.codes.ok:
print(response.content)
b'{"Description":"American Assets Trust, Inc. (the \\\u0093company\\\u0094) is a full service, vertically ..."}'
我认为字符串存储在他们的数据库中,就像\“以满足一些SQL转义协议。当我得到它时,转义斜杠与字符代码混合在一起,从而弄乱了编码。
看起来这些字符来自编码为cp1252的文本。可以解码它们
>>> bs = b'{"Description":"American Assets Trust, Inc. (the \\u0093company\\u0094) is a full service, vertically ..."}'
>>> d = json.loads(bs)
>>> s = d['Description']
>>> decoded = s.encode('latin-1').decode('cp1252')
>>> decoded
'American Assets Trust, Inc. (the “company”) is a full service, vertically ...'
但你必须使用str.replace
或str.translate
手动替换它们
>>> table = str.maketrans('“”', '""')
>>> decoded = s.encode('latin-1').decode('cp1252')
>>> decoded.translate(table)
'American Assets Trust, Inc. (the "company") is a full service, vertically ...'