python - 在 Python 中将 html 实体转换为 ascii

标签 python ascii

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

现在,我只真正知道如何在我需要 ASCII(我认为)时从这些实体创建 unicode,这样纯文本电子邮件才能正确读取带有重音字符之类的东西。我认为一个基本的例子是 html 实体“á”或 á 被编码为 ASCII。

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

最佳答案

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

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

关于python - 在 Python 中将 html 实体转换为 ascii,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1197981/

相关文章:

python - 如何使用python检查多边形内像素的颜色并删除包含白色像素的多边形?

python - 使用 Python 抓取 .aspx 表单

python - python 单元测试的基本测试用例类

elasticsearch - 在ElasticSearch中使用 token 化器“asciifolding”的“pattern”

尽管出现 UnicodeDecodeError,Python 3 itertools.islice 仍继续

python - 在 ubuntu 中安装 gensim 错误

Javascript 字符 (ASCII) 到十六进制

java - 无法将 Int 数组转换为 ASCII

php - url 中的未知字符 %252B

python - 根据排名为学生分配主题