4

我需要在 Python 中使用 HTML 实体将 unicode UTF-8 字符串编码为 ASCII。

要清楚:

source = u"Hello…"
wanted = "Hello…"

这不是解决方案:

as_ascii = source.encode('ascii', 'xmlcharrefreplace')

因为as_ascii将设置为Hello…- 即,使用 XML 字符引用,而不是 HTML 之一。

是否有 Python 模块/函数/实体字典可以:

  1. 使用 HTML 字符引用将 unicode 解码为 ASCII。
  2. 将具有 XML 字符引用的 ASCII 字符串替换为 HTML 字符引用(视情况而定)。
4

1 回答 1

2

示例程序(文件decode_to_entity.py):

#-*- coding: utf-8 -*-

import htmlentitydefs as entity

def decode_to_entity(s):
        t = ""
        for i in s:
                if ord(i) in entity.codepoint2name:
                        name = entity.codepoint2name.get(ord(i))
                        t += "&" + name + ";"
                else:
                        t += i
        return t



print(decode_to_entity(u"Hello…"))

和示例执行:

$ python decode_to_entity.py
Hello…
于 2013-10-17T19:34:48.163 回答