【问题标题】:Strange characters in string gotten from API can't decode从 API 获取的字符串中的奇怪字符无法解码
【发布时间】:2019-03-03 02:10:13
【问题描述】:

我正在创建一个从 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 转义协议。当我得到它时,转义斜杠会与字符代码混合,从而弄乱编码。

【问题讨论】:

  • Ascii2Uni 的一些变体可能会有所帮助。也许有一个 Python 绑定或端口。

标签: python python-3.x character-encoding


【解决方案1】:

看起来这些字符来自编码为 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.replacestr.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 ...'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2010-11-09
    • 2019-11-20
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多