繁体   English   中英

如何在 Python 中解码以“%u”(百分号 + u)开头的 unicode 字符串

[英]How to decode the unicode string starting with “%u” (percent symbol + u) in Python 3

我得到一些 HTML 代码,如下所示:

<new>8003,%u767E%u5723%u5E97,113734,%u4E50%u4E8B%u542E%u6307%u7EA2%u70E7%u8089%u5473,6924743915824,%u7F50,104g,3,21.57,-2.16,0,%u4E50%u4E8B,1</new>

我知道我可以在 Notepad++ 中找到并用“/u”替换所有“%u”,然后将其粘贴到 Python 控制台中,使其正确显示为汉字。 但是我怎样才能在 Python 中自动完成呢?

假设您的输入字符串包含“percent-u”编码字符,我们可以使用正则表达式替换和回调 function 找到并解码它们。

Percent-u 编码将 Unicode 代码点表示为四个十六进制数字: %u767E767E ⇒ 代码点 30334 ⇒ 百。

import re

def hex_to_char(hex_str):
    """ converts a single hex-encoded character 'FFFF' into the corresponding real character """
    return chr(int(hex_str, 16))

s = "<new>8003,%u767E%u5723%u5E97,113734,%u4E50%u4E8B%u542E%u6307%u7EA2%u70E7%u8089%u5473,6924743915824,%u7F50,104g,3,21.57,-2.16,0,%u4E50%u4E8B,1</new>"

percent_u = re.compile(r"%u([0-9a-fA-F]{4})")

decoded = percent_u.sub(lambda m: hex_to_char(m.group(1)), s)

print(decoded)

哪个打印

<new>8003,百圣店,113734,乐事吮指红烧肉味,6924743915824,罐,104g,3,21.57,-2.16,0,乐事,1</new>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM