gpt4 book ai didi

Javascript unescape() 与 Python urllib.unquote()

转载 作者:数据小太阳 更新时间:2023-10-29 05:57:58 29 4
gpt4 key购买 nike

看了各种帖子,好像是JavaScript的unescape()相当于 Pythons urllib.unquote() ,但是当我测试两者时,我得到不同的结果:

在浏览器控制台中:

unescape('%u003c%u0062%u0072%u003e');

输出: <br>

在 Python 解释器中:

import urllib
urllib.unquote('%u003c%u0062%u0072%u003e')

输出: %u003c%u0062%u0072%u003e

我希望 Python 也返回 <br> .关于我在这里缺少什么的任何想法?

谢谢!

最佳答案

%uxxxxnon standard URL encoding scheme urllib.parse.unquote() (Py 3)/urllib.unquote() (Py 2) 不支持。

它只是 ECMAScript ECMA-262 第三版的一部分;该格式被 W3C 拒绝,并且从未成为 RFC 的一部分。

您可以使用正则表达式来转换此类代码点:

try:
unichr # only in Python 2
except NameError:
unichr = chr # Python 3

re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: unichr(int(m.group(1), 16)), quoted)

这会解码 %uxxxx%uxx 形式的 ECMAScript 3rd ed 可以解码。

演示:

>>> import re
>>> quoted = '%u003c%u0062%u0072%u003e'
>>> re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: chr(int(m.group(1), 16)), quoted)
'<br>'
>>> altquoted = '%u3c%u0062%u0072%u3e'
>>> re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: chr(int(m.group(1), 16)), altquoted)
'<br>'

但如果可能,您应该避免完全使用编码。

关于Javascript unescape() 与 Python urllib.unquote(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23158822/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com