gpt4 book ai didi

使用用户提供的值替换 HTML 文件中的文本的 Python 脚本

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:27 24 4
gpt4 key购买 nike

我有一个 hmtl 文件,如下所示:

...
<!-- Special_ID -->
<p> stuff1 </p>
<p> stuff2 </p>
<!-- /Special_ID -->
...

我有一个 INI 文件:

[general]
param=stuff1
stuff2

如果用户编辑文件并更改 param值为 test ,我想将html文件更改为:

...
<!-- Special_ID -->
<p> test </p>
<!-- /Special_ID -->
...

目前,我正在做的是解析 INI 文件(Python 的 ConfigParser ),然后将部分(“general”)和选项(“param”)转换为启动和停止特殊 id,如上面的示例所示.

然后:

while we haven't found the start id:
just write a line to some temporary file

write our start id to the temp file
write out new value ("test") to the temp file # surround with <p>

loop through original file until we find the stop id
then write the stop id and the rest of the file to temp

replace original file with tmp file

有更聪明的方法吗?

也许 Python 模块已经做到了这一点。

我也不太喜欢要求 <!-- Special_ID --> ,但我没有使用网络框架(只是一个简单的应用程序),所以我不能只是做一个花哨的 <p py:for ...>...就像 TurboGears 中一样。

最佳答案

总体上不确定您当前提出的方法,但以下是如何替换特定注释后的所有 p 元素并插入新的 p 元素相反(使用 BeautifulSoup HTML 解析器)。这个想法是:

工作代码:

from bs4 import BeautifulSoup, Comment

data = """
<!-- Special_ID -->
<p> stuff1 </p>
<p> stuff2 </p>
<!-- /Special_ID -->
"""
soup = BeautifulSoup(data, "html.parser")

# find "Special_ID" comment
special_id = soup.find(text=lambda text: isinstance(text, Comment) and "Special_ID" in text)

# find all sibling "p" elements
for p in special_id.find_next_siblings("p"):
p.extract()

# create new "p" element
tag = soup.new_tag("p")
tag.string = "test"

# insert the new "p" element after the comment
special_id.insert_after(tag)

print(soup.prettify())

打印:

<!-- Special_ID -->
<p>
test
</p>
<!-- /Special_ID -->

关于使用用户提供的值替换 HTML 文件中的文本的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com