4

我需要使用 Python 将任何 html 实体转换为其 ASCII 等价物。我的用例是我正在清理一些用于构建电子邮件的 HTML,以从 HTML 创建纯文本电子邮件。

现在,我只有在需要 ASCII(我认为)时才真正知道如何从这些实体创建 unicode,以便纯文本电子邮件可以正确读取重音字符等内容。我认为一个基本的例子是 html 实体“& aacute;” 或 á 被编码为 ASCII。

此外,我什至不能 100% 确定 ASCII 是明文电子邮件所需要的。如您所知,我完全迷失了这种编码的东西。

4

4 回答 4

8

这是一个完整的实现,它也处理 unicode html 实体。你可能会发现它很有用。

它返回一个非 ascii 的 unicode 字符串,但如果您想要纯 ascii,您可以修改替换操作,以便将实体替换为空字符串。

def convert_html_entities(s):
    matches = re.findall("&#\d+;", s)
    if len(matches) > 0:
        hits = set(matches)
        for hit in hits:
            name = hit[2:-1]
            try:
                entnum = int(name)
                s = s.replace(hit, unichr(entnum))
            except ValueError:
                pass

    matches = re.findall("&#[xX][0-9a-fA-F]+;", s)
    if len(matches) > 0:
        hits = set(matches)
        for hit in hits:
            hex = hit[3:-1]
            try:
                entnum = int(hex, 16)
                s = s.replace(hit, unichr(entnum))
            except ValueError:
                pass

    matches = re.findall("&\w+;", s)
    hits = set(matches)
    amp = "&"
    if amp in hits:
        hits.remove(amp)
    for hit in hits:
        name = hit[1:-1]
        if htmlentitydefs.name2codepoint.has_key(name):
            s = s.replace(hit, unichr(htmlentitydefs.name2codepoint[name]))
    s = s.replace(amp, "&")
    return s 

编辑:添加了十六进制代码的匹配。我已经使用了一段时间了,并且遇到了我的第一个情况, ' 这是一个单引号/撇号。

于 2009-10-17T11:53:40.400 回答
2

ASCII 是美国信息交换标准代码,包括任何重音字母。您最好的选择是获取 Unicode(如您所说)并将其编码为 UTF-8(如果您正在处理严重编码错误的用户代理/客户端,可能是 ISO-8859-1 或一些奇怪的代码页,叹息) - - 该部分的内容类型标头与 text/plain 一起可以表达您选择使用的编码(我建议尝试 UTF-8,除非您已经明确证明它无法工作 - 现在几乎普遍支持它,而且更多比任何 ISO-8859 或“代码页”破解更灵活!)。

于 2009-07-29T04:10:44.107 回答
1

您可以使用htmlentitydefs包:

import htmlentitydefs
print htmlentitydefs.entitydefs['aacute']

基本上,entitydefs它只是一个字典,您可以通过在 python 提示符下打印它来查看:

from pprint import pprint 
pprint htmlentitydefs.entitydefs
于 2009-07-29T04:10:45.760 回答
0

我们搭建了一个带有agazso功能的小模块:

http://github.com/ARTFL/util/blob/master/ents.py

我们发现 agazso 的功能比 ent 转换的替代品更快。感谢您发布它。

于 2010-08-07T05:56:44.973 回答