【发布时间】:2021-06-21 13:56:29
【问题描述】:
我有一个如下所示的 HTML 文件:
<!DOCTYPE HTML>
<html>
<head>
<title>Sezione microbiologia</title>
<link rel="stylesheet" src="./style.css">
</head>
<body>
<div id="content">
<section id="main">
<!-- SOME CONTENT... -->
<h1>Prima diluizione</h1>
<p>Some content including "prima diluizione"...</p>
<h1>Seconda diluizione</h1>
<p>Some content including "seconda diluizione"...</p>
<h1>Terza diluizione</h1>
<p>Some content including "terza diluizione"...</p>
</section>
<section id="second">
<!-- SOME CONTENT... -->
</section>
<section id="third">
<!-- SOME CONTENT... -->
</section>
<section id="footer">
<!-- SOME CONTENT... -->
</section>
</div>
</body>
</html>
问题描述:
我正在尝试修改包含单词diluizione 的标题<h1> 以将该单词及其前缀替换为“Diluizione seriale”。我尝试使用 Python replace() 来做到这一点,问题是即使 <p> 段落中的行被截断,而我只想修改 h1 标记中的行。最重要的是,我还没有找到自动取出前缀的方法,即“Prima”、“Seconda”、“Terza”等。
我尝试过的代码
我目前想出了这个:
with open('./home.html') as file:
text = file.read()
if "diluizione" in text:
text = text.replace("diluizione", "diluizione seriale")
但是这个输出:
<div id="content">
<section id="main">
<!-- SOME CONTENT... -->
<h1>Prima diluizione seriale</h1>
<p>Some content including "prima diluizione seriale"...</p>
<h1>Seconda diluizione seriale</h1>
<p>Some content including "seconda diluizione seriale"...</p>
<h1>Terza diluizione seriale</h1>
<p>Some content including "terza diluizione seriale"...</p>
</section>
如您所见,即使<p> 标签中的文本也会受到影响,并且前缀仍然存在。
我的想要的输出是:
<div id="content">
<section id="main">
<!-- SOME CONTENT... -->
<h1>Diluizione seriale</h1>
<p>Some content including "prima diluizione"...</p>
<h1>Diluizione seriale</h1>
<p>Some content including "seconda diluizione"...</p>
<h1>Diluizione seriale</h1>
<p>Some content including "terza diluizione"...</p>
</section>
非常感谢任何帮助或建议,非常感谢。
【问题讨论】: