如何删除上述蟒蛇一定行的所有行

问题描述 投票:-1回答:2

我有一个HTML文件,其中我想删除线以上的所有行开始用绳子<!DOCTYPE html

例:

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=utf-8
Date: Sat, 22 Mar 2015 07:56:52 
Connection: close
Content-Length: 2959

<!DOCTYPE html...... extra lines ...

所以,当我搜索字符串出现的<!DOCTYPE我需要删除所有线路,包括那些空白这一行的上方。在linux中,我们在grep一个选项,它可以搜索上面和下面的线,然后将其删除。我们可以做Python中的类似的事情?

python parsing
2个回答
1
投票
stop = "<!DOCTYPE html"

with open('input.html') as infile, open('output.html', 'w') as outfile:
    buff = []
    for line in infile:
        if not line.strip():
            buff.append(line)
            continue
        if line.strip() == stop: break
        outfile.write(''.join(buff))
        buff = []
        outfile.write(line)

0
投票

不知道你的意思究竟是什么,但我想你的意思是你打开HTML文件,然后试图修改里面有什么?这可能是非正统的,但尝试打开它只是阅读,使用readlines方法()来获得并存储所有线路。过滤掉你不想要的线。然后关闭该文件,再次打开它来编写和只贴上里面的线(这将覆盖所有的文件在当前的内容)。这使您可以删除您不希望中间内也行。

© www.soinside.com 2019 - 2024. All rights reserved.