您好,我正在尝试删除文件中的一行,但想保留其余行。
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 会更健壮。
我是一名优秀的程序员,十分优秀!