将数字字符引用表示法转换为 unicode 字符串

问题描述 投票:0回答:2

是否有一种标准的(最好是 Pythonic 的)方法将

&#xxxx;
表示法转换为正确的 unicode 字符串?

例如,

מפגשי

应转换为:

מפגשי

这可以很容易地使用字符串操作来完成,但我想知道是否有一个标准库。

python unicode encoding
2个回答
10
投票

使用

HTMLParser.HTMLParser()

>>> from HTMLParser import HTMLParser
>>> h = HTMLParser()
>>> s = "מפגשי"
>>> print h.unescape(s)
מפגשי

它也是标准库的一部分。


但是,如果您使用的是 Python 3,则必须从

html.parser
:

导入
>>> from html.parser import HTMLParser
>>> h = HTMLParser()
>>> s = 'מפגשי'
>>> print(h.unescape(s))
מפגשי

0
投票

任何想要 Python 3.4+ 的解决方案,您可以使用

html.unescape
模块中的
html

import html

print(html.unescape('מפגשי'))

其他两种方法(Python 2 中的

HTMLParser.HTMLParser
和 Python 3 至 3.3 中的
html.parser.HTMLParser
)已被弃用并从当前版本的 Python 中删除。

© www.soinside.com 2019 - 2024. All rights reserved.