注:私は、ifという投稿後に実現最後の出現は01のない最後の行でしたの後にこのテクニックを置くと、次の最後のオカレンスが残されます。あなたが最初に出現した見つけるまで
まず、ファイルを反復する必要があるでしょう:
file = <OPEN FILE>
rep_line = "<this is repeated>\n"
beginning = "" #record all data until found
while True: #broken when rep_line is found in file (or end of file is reached)
line = file.readline()
if not line:
raise EOFError("reached end of file before finding first occurence")
beginning+=line
if line == rep_line:
break
rest = file.read() #you can read the rest after iterating over a few lines
が次にあなたがbeginning
を持っています最初の発生までを含むすべてのものが含まれており、rest
だから、rest
で行う必要があるのはcount
です。最後の時間以外はどのように時間を置き換えて置き換えてください。
reps = rest.count(rep_line)
new_text = beginning + rest.replace(rep_line,"",reps - 1)
# ^don't replace the last one
ただし、テキスト(例えば"hello <this is repeated>"
など)で終了し、これはまた、\ nは、右の行の前にあることを確認することで固定することができ、ラインピックアップします。この直接的なアプローチ:
reps = rest.count("\n"+rep_line)
new_text = beginning + rest.replace("\n"+rep_line,"\n",reps - 1)
#^replace with a single newline
は、ラインを読むを現在の行が最後と異なる場合、出力ファイルに書き出します。それ以外の場合は、行をスキップして空白行を書き込んでください。それ以上のことはありません。 –
それを空行に置き換えるか、行全体を削除しますか? –