首页 > 解决方案 > 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 之类的库或某种复杂的正则表达式字符串来完成此操作?

标签: pythonhtmlregexbeautifulsoup

解决方案


要替换 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>

推荐阅读