[英]Getting behaviour like Python 3 html unescape in Python 2
所以我遇到了一个问题,似乎 Python 2 (2.7.13) 根本没有为转义所有这些实体定义所需的 HTML 实体。
例如,在运行此脚本时:
# test_unescape.py
from six.moves.html_parser import HTMLParser
h = HTMLParser()
# Print in a tuple for clarity
print((h.unescape('£<	
∷'),))
根据 Python 版本,您会得到不同的结果。
蟒蛇2:
$ python test_unescape.py
(u'\xa3<	
∷',)
制表符、换行符和冒号被转义
蟒蛇3:
$ python3 test_unescape.py
('£<\t\n∷',)
所有未转义
我也不清楚为什么我在 Python 3 示例中得到两个冒号。
不手动定义所有丢失的实体(因此必须用未来的实体维护它......)的任何解决方法来获得 Python 3 版本或 Python 2 中的等效内容将不胜感激
我在这个库中找到了我的问题的答案
更具体地说,在位于html5lib.constants.entities
的完整实体列表中
import html5lib
def unescape_custom(s):
ents = html5lib.constants.entities
for e in ents:
if e[-1] != ';':
e += ';'
s = s.replace('&{}'.format(e), ents[e])
return s
结果:
# Python 2
>>> print((unescape_custom("£<	
∷"),))
(u'\xa3<\t\n\u2237',)
# Python 3
>>> print((unescape_custom("£<	
∷"),))
('£<\t\n∷',)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.