【Python Cookbook】S02E15 在文本中处理 HTML 和 XML 实体

目录

问题

我们如果想要将 HTML 实体以及 XML 实体内容替换成相对应的文本内容,怎么做?

解决方案

python 复制代码
s = "Elements are written as '<tag>txt</tag>'."

import html
print(html.escape(s))
print("-"*20, "Disable escaping of quotes", "-"*20)
print(html.escape(s, quote=False))

结果为

python 复制代码
Elements are written as &#x27;&lt;tag&gt;txt&lt;/tag&gt;&#x27;.
-------------------- Disable escaping of quotes --------------------
Elements are written as '&lt;tag&gt;txt&lt;/tag&gt;'.

其中,解析出的各结果解释如下:

  • &#x27 代表 "
  • &lt 代表 <
  • &gt 代表 >

在第二个输出中,因为我们在 html.escape() 函数中添加参数 quote=False ,所以在结果中并不会解析 " 引号~

如果要生成 ASCII 文本,并且想针对非 ASCII 字符将其对应的字符编码实体嵌入到文本中,可以在各种同 I/O 相关的函数中使用 errors='xmlcharrefreplace' 参数来实现。

python 复制代码
s = "Spicy Jalapeño"
print(s.encode("ascii", errors="xmlcharrefreplace"))

结果:

python 复制代码
b'Spicy Jalape&#241;o'

如果由于某种原因在得到的文本中带有一些实体,而我们又想要得到其内容,可以利用 HTML 以及 XML 解析器自带的功能函数和方法来完成。

python 复制代码
s = "Spicy &quot;Jalape&#241;o&quot"
import html
print(html.unescape(s))
t = "The prompt is &gt;&gt;&gt;"
from xml.sax.saxutils import unescape
print(unescape(t))

结果

python 复制代码
Spicy "Jalapeño"
The prompt is >>>

讨论

在生成 HTMLXML 文档时,适当的对特殊字符做转义处理推荐使用如 html.escape() 这样的函数。

而如果要反过来,即将 HTMLXML 实体转换成对应的字符,推荐使用像 html.unescape()xml.sax.saxutils.unescape() 这样的函数。

相关推荐
haosend30 分钟前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽42 分钟前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_18 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang20 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮20 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling20 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮1 天前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽1 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
willow1 天前
html5基础整理
html