如何解决在 Python 2 中获得类似 Python 3 html unescape 的行为
所以我遇到了一个问题,似乎 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 版本。
Python 2:
$ python test_unescape.py
(u'\xa3<	
∷',)
制表符、换行符和冒号被转义
Python 3:
$ python3 test_unescape.py
('£<\t\n∷',)
全部未转义
我也不清楚为什么我在 Python 3 示例中得到两个冒号。
在不手动定义所有缺失实体的情况下获得 Python 3 版本或 Python 2 中的等效内容的任何解决方法(因此必须使用未来的实体维护它...)将不胜感激
解决方法
我在 this library
中找到了问题的答案更具体地说是位于 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∷',)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。