Extracting multiple strings using Pythons's regular expression

后端 未结 3 491
北荒
北荒 2021-01-27 21:42

I have a log file having the following output and I have shortened it as it goes to thousands of lines:

Time = 1

smoothSolver:  Solving for Ux, Initial residual         


        
3条回答
  •  轮回少年
    2021-01-27 22:18

    Your code is writing over iteration_time in every iteration of the for loop. That is the problem. You will need to stop populating this variable after it has been successfully populated for the first find.

    To do this, in the for loop do a test for iteration_time and only if it is non- existent or None do the regex search for Time. You can do soemthing like this:

    contCumulative_0_out = open('contCumulative_0', 'w+')
    
    with open(logFile, 'r') as logfile_read:
        iteration_time = None
        for line in logfile_read:
            line = line.rstrip()
            time_match = re.findall(r'^Time = ([0-9]+)', line)
            if time_match:
                iteration_time = time_match
                print iteration_time
            else:  # Because if there is time_match, there is no 'cumulative = ...'
                contCumulative_0 = re.search(r'cumulative = ((\d|.)+)', line)
                if contCumulative_0:        
                    cumvalue = contCumulative_0.groups(1)
                    # You can check and use iteration_time here
                    contCumulative_0_out.write('\n'.join(cumvalue))
    

    Hope this helps.

提交回复
热议问题