我需要使用 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/