在Python中将html实体转换为ascii

2024-04-26 12:12:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

此外,我甚至不能百分之百确定,ASCII是我需要的明文电子邮件。如你所知,我完全迷失在这种编码上了。


Tags: 文本实体内容编码电子邮件htmlasciiunicode
3条回答

您可以使用htmlentitydefs包:

import htmlentitydefs
print htmlentitydefs.entitydefs['aacute']

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

from pprint import pprint 
pprint htmlentitydefs.entitydefs

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

下面是一个完整的实现,它还处理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 

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

相关问题 更多 >