Python:テキストファイル内の行を戻る

Python:テキストファイル内の行を戻る

ランダムなテキストと2つのユニークなタグを含むテキストファイルを想像してください。

01 text text text
02 text text text
03 __DELETE_THIS_FIRST__
04 text text text
05 text text text
06 text text text
07 text text text
08 __DELETE_THIS_LINE_SECOND__
09 a few
10 interesting
11 lines follow
12 __DELETE_THIS_LINE_THIRD__
13 text text text
14 text text text
15 text text text
16 text text text
17 __DELETE_THIS_LINE_FIRST__
18 text text text
19 text text text
20 text text text
21 text text text
22 __DELETE_THIS_LINE_SECOND__
23 even
24 more
25 interesting lines
26 __DELETE_THIS_LINE_THIRD__

ENDタグとthr THIRDタグの間の興味深い行を移動するPython式が欲しいです。より早いBEGIN は、3 つのマークすべてを表示および削除します。結果は次のとおりです。

01 text text text
02 text text text
09 a few
10 interesting
11 lines follow
04 text text text
05 text text text
06 text text text
07 text text text
13 text text text
14 text text text
15 text text text
16 text text text
23 even
24 more
25 interesting lines
18 text text text
19 text text text
20 text text text
21 text text text

これらの3つのタグは常に3つのタグであり、ファイルに複数回表示されます。 FIRSTタグは常にSECONDタグの前に表示され、SECONDタグは常にTHIRDタグの前に表示されます。

どんなアイデアがありますか?

関連:126325

ベストアンサー1

以下は、タスクを実行するPythonスクリプトです。

#! /usr/bin/env python

buffer = []
markerBuffer = []

beginFound = False
endFound = False

begin_marker = "__DELETE_THIS_LINE_FIRST__"
end_marker = "__DELETE_THIS_LINE_SECOND__"

line_count_marker = "__DELETE_THIS_LINE_THIRD__"

with open('hello.txt') as inFile:
    with open('hello_cleaned.txt', 'w') as outFile:
        for line in inFile:
            if begin_marker in line and delete_marker in line:
                beginFound = True
                continue
            if end_marker in line and delete_marker in line:
                assert beginFound is True
                endFound = True
                continue
            if beginFound and not endFound:
                markerBuffer.append(line)
                continue
            if beginFound and endFound and line_count_marker not in line:
                buffer.append(line)
                continue
            if beginFound and endFound and line_count_marker in line:
                for mLine in markerBuffer:
                    buffer.append(mLine)

                markerBuffer = []
                beginFound = False
                endFound = False
                continue
            if not beginFound and not endFound:
                buffer.append(line)
                continue
        for line in buffer:
            outFile.write(str(line))

おすすめ記事