【发布时间】:2013-10-17 18:57:36
【问题描述】:
我需要在 Python 中使用 HTML 实体将 unicode UTF-8 字符串编码为 ASCII。
要明确:
source = u"Hello…"
wanted = "Hello…"
这不是解决方案:
as_ascii = source.encode('ascii', 'xmlcharrefreplace')
因为as_ascii 将被设置为Hello… - 即使用XML 字符引用,而不是HTML。
是否有 Python 模块/函数/实体字典可以:
- 使用 HTML 字符引用将 unicode 解码为 ASCII。
- 将包含 XML 字符引用的 ASCII 字符串替换为 HTML 字符引用(视情况而定)。
【问题讨论】:
-
对于实体字典,
htmlentitydefs.codepoint2name对方法 2 有帮助吗?htmlentitydefs.codepoint2name[8230] == "hellip". -
是的!谢谢。我可以使用 htmlentitydefs!
-
我不得不从 htmlentitydefs 包中取出一些元素,但我想出了这个 -- gist.github.com/jvanasco/7030697
-
数字字符引用在 HTML 中与在 XML 中一样有效,您可能需要它们用于所有没有 HTML 特定实体的字符。
-
是的,我知道它们在渲染时是等价的。我特别想要 HTML 实体。
标签: python unicode encoding utf-8