我想将 HTML 实体转换回人类可读的格式,例如'£'
到 '£','°'
到 '°' 等
我已经阅读了几篇关于这个问题的帖子
Converting html source content into readable format with Python 2.x
Decode HTML entities in Python string?
Convert XML/HTML Entities into Unicode String in Python
根据他们的说法,我选择使用未记录的函数 unescape(),但它对我不起作用...
我的代码示例如下:
import HTMLParser
htmlParser = HTMLParser.HTMLParser()
decoded = htmlParser.unescape('© 2013')
print decoded
当我运行这个 python 脚本时,输出仍然是:
© 2013
代替
© 2013
我正在使用 Python 2.X,在 Windows 7 和 Cygwin 控制台上工作。我用谷歌搜索并没有发现任何类似的问题..任何人都可以帮我解决这个问题吗?
最佳答案
显然 HTMLParser.unescape
是一个 bit more primitive之前Python 2.6 .
python 2.5:
>>> import HTMLParser
>>> HTMLParser.HTMLParser().unescape('©')
'©'
python 2.6/2.7:
>>> import HTMLParser
>>> HTMLParser.HTMLParser().unescape('©')
u'\xa9'
更新:Python 3.4+:
>>> import html
>>> html.unescape('©')
'©'
参见 2.5 implementation与 2.6 implementation 相比/2.7 implementation
关于python - HTMLParser.HTMLParser().unescape() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17751439/