仅当第一行包含" 1 1"时,删除特定单词(COMPDAT)后的第一行。用Python

时间:2017-04-28 08:59:50

标签: python

我问了类似的问题How to delete one line after the specific word with Python。但是,我想再增加一个条件。所以我想删除第一行有两个条件:

  1. 在" COMPDAT"。
  2. 之后
  3. 仅当第一行包含" 1"第4项和第5项。
  4. 例如:

    COMPDAT

    ' 9850' 125 57 1 1 OPEN /

    我在上一个问题中建议的代码仅适用于条件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()
    

    如何更改此代码以满足第二个条件?

    谢谢!

1 个答案:

答案 0 :(得分:0)

这基于my answer to your other question

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()

您需要考虑何时保持行而不是何时删除行