python - HTMLParser.HTMLParser().unescape() 不起作用

标签 python html unicode

我想将 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 implementation2.6 implementation 相比/2.7 implementation

关于python - HTMLParser.HTMLParser().unescape() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17751439/

相关文章:

Eclipse 中的 Python 文档

python - 在没有 xrandr 的情况下获取 Python 中每个显示器的显示计数和分辨率

javascript - 以编程方式打开 <select> 选择器

html - 跨浏览器音频到 Canvas 可视化

javascript - 使用 jquery 在我的站点中加载其他网页不起作用

html - 哪些字符可用于在 HTML 中显示的上/下三 Angular 形(没有茎的箭头)?

python - SciPy.sparse 迭代求解器 : No sparse right hand side support?

python - 如何膨胀gzipped,base64d字符串

sql-server - 如何将 UTF-8 平面文件导入 SQL Server 2008 R2?

python - pyQt 和 QTextEdit : Why are some unicode characters are shown, 其他不是吗?