Replace html entities with the corresponding utf-8 characters in Python 2.6

元气小坏坏 提交于 2019-12-03 17:57:58

问题


I have a html text like this:

<xml ... >

and I want to convert it to something readable:

<xml ...>

Any easy (and fast) way to do it in Python?


回答1:


Python 2.7

Official documentation for HTMLParser: Python 2.7

>>> import HTMLParser
>>> pars = HTMLParser.HTMLParser()
>>> pars.unescape('&copy; &euro;')
u'\xa9 \u20ac'
>>> print _
© €

Python 3

Official documentation for HTMLParser: Python 3

>>> from html.parser import HTMLParser
>>> pars = HTMLParser()
>>> pars.unescape('&copy; &euro;')
© €



回答2:


There is a function here that does it, as linked from the post Fred pointed out. Copied here to make things easier.

Credit to Fred Larson for linking to the other question on SO. Credit to dF for posting the link.




回答3:


Modern Python 3 approach:

>>> import html
>>> html.unescape('&copy; &euro;')
© €

https://docs.python.org/3/library/html.html



来源:https://stackoverflow.com/questions/730299/replace-html-entities-with-the-corresponding-utf-8-characters-in-python-2-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!