在Python中将html实体转换为ascii

aez*_*ell 4 python ascii

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

现在,当我需要ASCII(我认为)时,我才真正知道如何从这些实体创建unicode,以便明文电子邮件能够正确读取带有重音字符的内容.我认为一个基本的例子是html实体"á" 或者á被编码为ASCII.

此外,我甚至不能确定ASCII是明文电子邮件所需要的.你可以告诉我,我完全迷失在这个编码的东西上.

小智 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 
Run Code Online (Sandbox Code Playgroud)

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