python - Python - 在 HTML 中搜索和替换分解的文本
问题描述
我一直在使用一种工具将 pdf 文档转换为 HTML,以便可以更轻松地编辑它们,同时保留尽可能多的格式。我需要做的是用文本“[已编辑]”替换某些短语,问题是这个文本被随机标签(主要是跨标签)不可预测地分解,所以我不能轻易地使用查找和替换。
例如,我需要从此 html 片段中替换文本“要删除的敏感信息”:
<span class="fs4 fc2">Sensitive<span class="_ _b"> </span>Information to Re<span class="_ _c"></span>move</span>
有了这个:
<span class="fs4 fc2">[REDACTED]</span>
有什么方法可以使用 Beautiful Soup 之类的库或某种复杂的正则表达式字符串来完成此操作?
解决方案
要替换 HTML 文档中的文本,您可以使用BeautifulSoup 提供clear()
的方法(手册页):append()
data = """<span class="fs4 fc2">Sensitive<span class="_ _b"> </span>Information to Re<span class="_ _c"></span>move</span>"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'lxml')
secret_string = "Sensitive Information to Remove"
redacted_string = "[REDACTED]"
while True:
s = soup.body.find(lambda t: t.text==secret_string)
if not s:
break
s.clear()
s.append(redacted_string)
print(soup)
这将打印:
<html><body><span class="fs4 fc2">[REDACTED]</span></body></html>
推荐阅读
- java - 通过将部分名称替换为哈希码来缩短长名称
- javascript - 单击时使用 jquery 清除列表
- maven - 如何通过多模块方法使用另一个项目战来创建耳朵
- c++ - 如何在 recursive_directory_iterator 上使用 parallel_for?
- go - 是否有任何支持事务的 Kafka Go 客户端?
- c++ - C++ 中的洗牌向量
- oracle - Oracle 12c 中如何并行调用多个过程?
- java - 在聊天应用程序中编辑文本发送功能
- r - Datatable DT包R - 嵌入ppt
- django - 为什么我们要使用 django-webpack-loader?