如何在Python 3.1中取消转义字符串中的HTML实体?
我到处找了找,只找到针对 Python 2.6 及更早版本的解决方案,完全没有关于如何在 Python 3.X 中做到这一点的内容。(我只有 Win7 的电脑可用。)
我必须能在 3.1 版本中做到这一点,最好不依赖外部库。目前,我安装了 httplib2,并且可以使用命令提示符中的 curl(我就是通过这个获取网页的源代码)。不幸的是,curl 似乎无法解码 HTML 实体,我在文档中找不到解码的命令。
是的,我尝试过让 Beautiful Soup 工作,很多次都没有成功在 3.X 中。如果你能提供明确的步骤,让我在 Windows 环境下使用 Python 3 成功运行它,我会非常感激。
所以,简单来说,我需要把像这样的字符串:Suzy & John
转换成这样的字符串:"Suzy & John"。
6 个回答
8
看起来我的声望不够高,只能发这个帖子。unutbu的回答并没有处理引号的转义问题。我找到的唯一能做到这一点的就是这个函数:
import re
from htmlentitydefs import name2codepoint as n2cp
def decodeHtmlentities(string):
def substitute_entity(match):
ent = match.group(2)
if match.group(1) == "#":
return unichr(int(ent))
else:
cp = n2cp.get(ent)
if cp:
return unichr(cp)
else:
return match.group()
entity_re = re.compile("&(#?)(\d{1,5}|\w{1,8});")
return entity_re.subn(substitute_entity, string)[0]
这个函数我是在这个 页面上找到的。
15
你可以使用 xml.sax.saxutils.unescape
来实现这个功能。这个模块是Python标准库的一部分,可以在Python 2.x和Python 3.x之间通用。
>>> import xml.sax.saxutils as saxutils
>>> saxutils.unescape("Suzy & John")
'Suzy & John'
248
你可以使用这个函数 html.unescape:
在 Python3.4及以上版本(感谢J.F. Sebastian的更新):
import html
html.unescape('Suzy & John')
# 'Suzy & John'
html.unescape('"')
# '"'
在 Python3.3 或更早的版本:
import html.parser
html.parser.HTMLParser().unescape('Suzy & John')
在 Python2:
import HTMLParser
HTMLParser.HTMLParser().unescape('Suzy & John')