python - 将子字符串替换为子串 在美丽汤
问题描述
我正在尝试修改现有的 html 文件,以便将特定的关键字打印为强(无论它们出现在哪里)。
我的尝试:
from bs4 import BeautifulSoup as soup
txt = """<html><head><style></style></head><body><h2>"This is my keyword</h2><table><tr><td>This could be another instance of the keyword.</td></tr></table></body></html>"""
buzz_words = ["keyword", "apples"]
htmlSoup = soup(txt, features="html.parser")
for word in buzz_words:
target = htmlSoup.find_all(text=re.compile(r"" + re.escape(word)))
for v in target:
v.replace_with(v.replace(word, "".join(["<strong>", word, "</strong>"])))
print(str(htmlSoup))
结果:
This is my < ;strong> ;keyword< ;/strong> ;(spaces added by me)
期望的结果:
This is my <strong>keyword</strong>
解决方案
尝试以下
from bs4 import BeautifulSoup as soup
import re
import html
txt = """<html><head><style></style></head><body><h2>"This is my keyword</h2><table><tr><td>This could be another instance of the keyword.</td></tr></table></body></html>"""
buzz_words = ["keyword", "apples"]
htmlSoup = soup(txt, features="html.parser")
for word in buzz_words:
target = htmlSoup.find_all(text=re.compile(r"" + re.escape(word)))
for v in target:
v.replace_with(v.replace(word, "".join(["<strong>", word, "</strong>"])))
print(html.unescape(str(htmlSoup.prettify())))
推荐阅读
- android - 如何搜索或过滤列表
来自 JSON 数组? - flutter - 颤振无法导入`flutter_webrtc.dart`
- python - 当我尝试使用 tkinter 将图像加载到画布上时,是什么导致错误“未知选项“pyimage1””?
- javascript - 试图从 Point A LLA 的角度将 Point B LLA 转换为 ECEF
- firebase - 从 Firebase 控制台手动删除文档而不删除子集合时,我应该怎么做才能触发 onDelete firebase 功能?
- python - 在python中将日期转换为列表
- docker - 一个运行 Apache 的容器内的多个站点:来自外部的虚拟主机?
- c# - 如何返回 DispatcherOperation
从模拟对象 - sql - SQL Server CTE 层次结构数据类型转换
- angular - 如何在 Angular 中翻译库而不在应用程序中初始化翻译服务?