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
您可以使用htmlentitydefs包:
基本上,
entitydefs
只是一个字典,您可以通过在python提示符下打印它来看到这一点:ASCII是美国标准的信息交换代码,不包含任何重音字母。你最好的办法是获得Unicode(你说你可以)并将其编码为UTF-8(可能是ISO-8859-1或一些奇怪的代码页,如果你正在处理严重编码错误的用户代理/客户端,叹气)--该部分的内容类型头和文本/纯文本可以表示您选择使用的编码(我建议您尝试使用UTF-8,除非您已经明确证明它无法工作--它现在几乎是普遍支持的,而且比任何ISO-8859或“codepage”黑客都灵活得多!)。
下面是一个完整的实现,它还处理unicode html实体。你可能会发现它很有用。
它返回一个不是ascii的unicode字符串,但是如果您想要纯ascii,您可以修改替换操作,以便将实体替换为空字符串。
编辑:为十六进制代码添加匹配。我用这个已经有一段时间了,遇到了我的第一个情况,是一个单引号/撇号。
相关问题 更多 >
编程相关推荐