Python 2.5.2: 删除包含两个具体字符串之间的内容

0 投票
5 回答
3460 浏览
提问于 2025-04-15 21:15

有没有什么方法可以删除两行之间的内容,这两行包含两个特定的字符串?

我的意思是:我想删除文本文件中“heaven”和“hell”之间的任何内容,文本文件的内容是:

I'm in heaven
foobar
I'm in hell

在执行我提到的脚本或函数后,文本文件将变为空。

5 个回答

0

你可以用正则表达式做类似下面的事情。虽然可能还有更有效的方法,因为我自己也在学习很多Python,但这个方法应该是可以用的。

import re

f = open('hh_remove.txt')
lines = f.readlines()

pattern1 = re.compile("heaven",re.I)
pattern2 = re.compile("hell",re.I)

mark1 = False
mark2 = False

for i, line in enumerate(lines):
    if pattern1.search(line) != None:
        mark1 = True
        set1 = i
    if pattern2.search(line) != None:
        mark2 = True
        set2 = i+1
    if ((mark1 == True) and (mark2 == True)):
        del lines[set1:set2]
        mark1 = False
        mark2 = False

f.close()
out = open('hh_remove.txt','w')
out.write("".join(lines))
out.close()
1

看起来你说的“删除”其实是指“在原地重写输入文件”(或者让它看起来像是这样做的;-),在这种情况下,fileinput.input 可以帮上忙:

import fileinput
writing = True
for line in fileinput.input(['thefile.txt'], inplace=True):
    if writing:
        if 'heaven' in line: writing = False
        else: print line,
    else:
        if 'hell' in line: writing = True
3

使用一个标志来表示你是否正在写入。

from __future__ import with_statement

writing = True

with open('myfile.txt') as f:
    with open('output.txt') as out:
        for line in f:
            if writing:
                if "heaven" in line:
                    writing = False
                else:
                    out.write(line)
            elif "hell" in line:
                writing = True    
os.remove('myfile.txt')
os.rename('output.txt', 'myfile.txt')

编辑

正如extraneon在评论中提到的,要求是要删除两个具体字符串之间的行。这意味着如果找不到第二个(结束)字符串,就不应该删除任何内容。可以通过保持一个行的缓冲区来实现这个功能。如果找到了结束字符串 "I'm in hell",这个缓冲区就会被丢弃;但如果到达文件末尾时还没有找到它,那么整个内容都必须写入文件。

示例:

I'm in heaven
foo
bar

应该保留整个内容,因为没有结束标签,而问题中提到的是在两行之间

这里有一个完整的示例:

from __future__ import with_statement

writing = True
with open('myfile.txt') as f:
    with open('output.txt') as out:
        for line in f:
            if writing:
                if "heaven" in line:
                    writing = False
                    buffer = [line]
                else:
                    out.write(line)
            elif "hell" in line:
                writing = True
            else:
                buffer.append(line)
        else:
            if not writing:
                #There wasn't a closing "I'm in hell", so write buffer contents
                out.writelines(buffer)

os.remove('myfile.txt')
os.rename('output.txt', 'myfile.txt')

撰写回答