HTML 实体代码到文本 [英] HTML Entity Codes to Text

查看:23
本文介绍了HTML 实体代码到文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道在 Python 中将带有 HTML 实体代码的字符串(例如 &lt; &)转换为普通字符串(例如< &)?

cgi.escape() 将转义字符串(效果不佳),但没有 unescape().

解决方案

HTMLParser 具有标准库中的功能.不幸的是,它没有记录:

(Python2 文档)

<预><代码>>>>导入 HTMLParser>>>h= HTMLParser.HTMLParser()>>>h.unescape('alpha &lt; &beta;')u'alpha <u03b2'

(Python 3 文档)

<预><代码>>>>导入 html.parser>>>h = html.parser.HTMLParser()>>>h.unescape('alpha &lt; &beta;')'阿尔法<u03b2'

htmlentitydefs 已记录在案,但需要您做很多自己的工作.

如果您只需要 XML 预定义实体(lt、gt、amp、quot、apos),您可以使用 minidom 来解析它们.如果您只需要预定义的实体而不需要数字字符引用,您甚至可以使用普通的旧字符串替换来提高速度.

Does anyone know an easy way in Python to convert a string with HTML entity codes (e.g. &lt; &amp;) to a normal string (e.g. < &)?

cgi.escape() will escape strings (poorly), but there is no unescape().

解决方案

HTMLParser has the functionality in the standard library. It is, unfortunately, undocumented:

(Python2 Docs)

>>> import HTMLParser
>>> h= HTMLParser.HTMLParser()
>>> h.unescape('alpha &lt; &beta;')
u'alpha < u03b2'

(Python 3 Docs)

>>> import html.parser
>>> h = html.parser.HTMLParser()
>>> h.unescape('alpha &lt; &beta;')
'alpha < u03b2'

htmlentitydefs is documented, but requires you to do a lot of the work yourself.

If you only need the XML predefined entities (lt, gt, amp, quot, apos), you could use minidom to parse them. If you only need the predefined entities and no numeric character references, you could even just use a plain old string replace for speed.

这篇关于HTML 实体代码到文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆