[英]How can I get only the line for the first occurrence of a word after a specific line in Python?
[英]Delete the first line after the specific word (COMPDAT) only if this first line contains “1 1” with Python
我問了類似的問題, 如何用Python刪除特定單詞后的一行 。 但是,我想再添加一個條件。 所以我想有兩個條件來刪除第一行:
例如:
COMPDAT
'9850'125 57 1 1打開/
我上一個問題中建議的代碼僅適用於條件1:
input_file = open("input.txt", 'r')
prev_line = False
lines =[]
for line in input_file:
if not prev_line:
lines.append(line)
prev_line=False
if "COMPDAT" in line:
prev_line=True
input_file.close()
input_file = open("input.txt", 'w')
for line in lines:
input_file.write(line)
input_file.close()
如何更改此代碼以滿足第二個條件?
謝謝!
這是基於我對您其他問題的回答
def line_and_line_before(file):
prev_line = None
for line in file:
yield (prev_line, line)
prev_line = line
def has_ones(line):
splitted_line = line.split(" ")
return len(splitted_line) > 4 and splitted_line[3] == '1' and splitted_line[4] == '1'
input_file = open("input.txt", 'r')
lines = []
for prev_line, line in line_and_line_before(input_file):
if (not prev_line or "COMPDAT" not in prev_line) or not has_ones(line):
lines.append(line)
input_file.close()
input_file = open("input.txt", 'w')
for line in lines:
input_file.write(line)
input_file.close()
您需要考慮何時保留行而不是何時除去行 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.