Перейти в следующую строку в readlines внутри цикла for - PullRequest
1 голос
/ 19 июня 2019

Я пишу код для извлечения чего-то полезного из очень большого Source.txt файла.Пример моего исходного тестового файла приведен ниже:

Test case AAA
Current Parameters:
    Some unique param : 1
    Some unique param : 2
    Some unique param :     3
    Some unique param : 4
*A line of rubbish*
*Another line of rubbish*
*Yet another line of rubbish*
*More and more rubbish*
Test AAA PASS
Test case BBB
Current Parameters:
    Some unique param : A
    Some unique param : B
    Some unique param :     C
    Some unique param : D
*A line of rubbish*
*Another line of rubbish*
*Yet another line of rubbish*
*More and more rubbish*
Test BBB PASS

Теперь я пишу код для извлечения только Test case и Current Parameters:

processed = []

def main():
    source_file = open("Source.txt","r") #Open the raw trace file in read mode
    if source_file.mode == "r":
        contents = source_file.readlines()   #Read the contents of the file
        processed_contents = _process_content(contents)
        output_file = open("Output.txt","w")
        output_file.writelines(processed_contents)
        pass

def _process_content(contents):
    for raw_lines in contents:
        if "Test case" in raw_lines:
            processed.append(raw_lines)
        elif "Current Parameters" in raw_lines:
            processed.append(raw_lines)
            #I am stuck here
        elif "PASS" in raw_lines or "FAIL" in raw_lines:
            processed.append(raw_lines)
            processed.append("\n")
    return processed

#def _process_parameters():


if __name__ == '__main__':
    main()

после строкиCurrent Parameters, я хотел получить каждый из Some unique param, который не всегда будет одинаковым, и добавить в список processed, чтобы он также был отмечен в моем файле Output.txt

Мой желаемый вывод:

Test case AAA
Current Parameters:
    Some unique param : 1
    Some unique param : 2
    Some unique param :     3
    Some unique param : 4
    Test AAA PASS
Test case BBB
Current Parameters:
    Some unique param : A
    Some unique param : B
    Some unique param :     C
    Some unique param : D
    Test BBB PASS

Если вы видите, я хотел удалить все мусорные линии.Обратите внимание, что в моем Source.txt много мусора.Я не уверен, как перейти к следующему raw_lines оттуда.Ценю вашу помощь.

Ответы [ 4 ]

1 голос
/ 19 июня 2019

Вы можете использовать обратную ссылку на регулярное выражение (например, \2), чтобы разделить контрольные примеры ( regex101 ):

import re

data = '''Test case AAA
Current Parameters:
    Some unique param : 1
    Some unique param : 2
    Some unique param :     3
    Some unique param : 4
*A line of rubbish*
*Another line of rubbish*
*Yet another line of rubbish*
*More and more rubbish*
Test AAA PASS
Test case BBB
Current Parameters:
    Some unique param : A
    Some unique param : B
    Some unique param :     C
    Some unique param : D
*A line of rubbish*
*Another line of rubbish*
*Yet another line of rubbish*
*More and more rubbish*
Test BBB PASS'''

for g in re.findall(r'(^Test case ([A-Za-z]+)\s+Current Parameters:(?:[^:]+:.*?$)*)+.*?(Test \2 (PASS|FAIL))', data, flags=re.DOTALL|re.M):
    print(g[0])
    print(g[2])

Печать:

Test case AAA
Current Parameters:
    Some unique param : 1
    Some unique param : 2
    Some unique param :     3
    Some unique param : 4
Test AAA PASS
Test case BBB
Current Parameters:
    Some unique param : A
    Some unique param : B
    Some unique param :     C
    Some unique param : D
Test BBB PASS
1 голос
/ 19 июня 2019

Это один из подходов с использованием Regex.

Ex:

import re

result = []
with open(filename) as infile:
    for raw_lines in infile:
        if "Test case" in raw_lines:
            result.append(raw_lines)
        if "Current Parameters" in raw_lines:
            result.append(raw_lines)
            raw_lines = next(infile)                        #next() to move to next line. 
            while True:
                m = re.search(r"(?P<params>\s*\w+\s*:\s*\w+\s*)", raw_lines)    
                if not m:
                    break
                result.append(m.group("params"))
                raw_lines = next(infile)
        if "PASS" in raw_lines or "FAIL" in raw_lines:
            result.append(raw_lines)
            result.append("\n")
print(result)

Выход:

['Test case AAA\n',
 'Current Parameters:\n',
 ' param : 1\n',
 ' param : 2\n',
 ' param :     3\n',
 ' param : 4\n',
 'Test AAA PASS\n',
 '\n',
 'Test case BBB\n',
 'Current Parameters:\n',
 ' param : A\n',
 ' param : B\n',
 ' param :     C\n',
 ' param : D\n',
 'Test BBB PASS',
 '\n']
1 голос
/ 19 июня 2019

Трудно сказать наверняка, сработает ли это, потому что я ничего не знаю о формате линий мусора, но я думаю, что вы можете просто проверить, содержит ли строка "Param", как вы ' делаю для других строк:

def _process_content(contents):
    for raw_line in contents:
        if "Test case" in raw_line:
            processed.append(raw_line)
        elif "Current Parameters" in raw_line:
            processed.append(raw_line)
        elif "Param" in raw_line:
            processed.append(raw_line)
        elif "PASS" in raw_line or "FAIL" in raw_lines:
            processed.append(raw_line)
            processed.append("\n")
    return processed
0 голосов
/ 19 июня 2019

Вы можете использовать str.startswith(), чтобы отфильтровать нужные вам строки, затем снова переписать эти строки в файл. Я также разделил бы строку на ":" и проверил бы, что длина равна 2, чтобы найти параметры. Также было бы безопасно преобразовать строки во все строчные буквы, так что вы можете выполнять сопоставление без учета регистра, так что он не думает, что "Test" - это не то же самое, что "test".

Демо-версия:

lines = []
with open("source.txt") as f:
    for line in f:
        lowercase = line.lower()
        if (
            lowercase.startswith("test")
            or lowercase.startswith("current parameters:")
            or len(lowercase.split(":")) == 2
        ):
            lines.append(line)

with open("source.txt", mode="w") as o:
    for line in lines:
        o.write(line)

source.txt:

Test case AAA
Current Parameters:
    Some unique param : 1
    Some unique param : 2
    Some unique param :     3
    Some unique param : 4
Test AAA PASS
Test case BBB
Current Parameters:
    Some unique param : A
    Some unique param : B
    Some unique param :     C
    Some unique param : D
Test BBB PASS
...