gpt4 book ai didi

python - 删除文件的特​​定行

转载 作者:太空宇宙 更新时间:2023-11-03 15:12:11 25 4
gpt4 key购买 nike

您好,我正在尝试删除文件中的一行,但想保留其余行。

f = open("myfile.html").read()
lines = f.readlines()
a = findall('<h2>\$.*', f)
f.close()
f = open("myfile.html","w")
for line in lines:
if line!= a[0]:
f.write(line)
f.close()

当我使用上面的代码时,我的 html 文件中的所有其他行都被删除。

尝试删除的文本:

        <h2>Thank you</h2>
<h2>Please come again</h2> #Get rid of this line

最佳答案

试试这个:

with open("myfile.html", "w+") as f:
content = f.read()
f.write(re.sub(r'<\s*h2[^>]*>(.*?)<\s*/\s*h2>', '', content))

但正如 @Willem Van Onsem 所建议的,不要对 XML/HTML 使用正则表达式,使用 XML 解析器、BeautifulSoup 的 lxml 会更健壮。

关于python - 删除文件的特​​定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44136493/

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