Junior
Junior

Reputation: 27

How to get previous line in current line(python)?

['00:00:00,210', '00:00:00,329']
['00:00:00,329', '00:00:04,230'] #the start time is same from previous line of end time, don't edit
['00:00:05,990', '00:00:08,099'] #the start time is different from previous line of end time, have to edit 
['00:00:08,099', '00:00:11,719'] #the start time is same from previous line of end time, don't edit
['00:00:15,480', '00:00:17,460'] #the start time is different from previous line of end time, have to edit 
['00:00:17,460', '00:00:19,500'] #the start time is same from previous line of end time, don't edit
['00:00:19,500', '00:00:21,480'] #the start time is same from previous line of end time, don't edit
['00:00:23,970', '00:00:26,160'] #the start time is different from previous line of end time, have to edit 
['00:00:28,800', '00:00:31,710'] #the start time is different from previous line of end time, have to edit 
['00:00:33,960', '00:00:36,059'] #the start time is different from previous line of end time, have to edit 
['00:00:38,430', '00:00:40,379'] #the start time is different from previous line of end time, have to edit 

I want to edit video time(srt file), but I only know how to split from "-->" , because I can't think of a way to get the time of the previous line when I am in current line.

for line in file:
    if re.match(r'\d{1,2}:\d{1,2}:\d{1,2},\d{1,3} --> \d{1,2}:\d{1,2}:\d{1,2},\d{3}',line):
        line = line.strip()  #remove space
        time_list =[i for i in line.split(' --> ')]   #use --> to split

        for x in [time_list]:      #I think this line starts out wrong
            previous_line_end_time=time_list[1]
        if time_list[0]==previous_line_end_time:

Upvotes: 0

Views: 945

Answers (1)

Ewerton Xavier
Ewerton Xavier

Reputation: 151

Just like Julia commented you can store the previous line value outside the loop. Besides, if the second for loop is only to update previous line, you can remove it and update it at the end of you for loop, like this:

previous_line_end_time = '00:00:00,000'
for line in file:
    if re.match(r'\d{1,2}:\d{1,2}:\d{1,2},\d{1,3} --> \d{1,2}:\d{1,2}:\d{1,2},\d{3}',line):
        line = line.strip()  #remove space
        time_list = list(line.split(' --> '))   #use --> to split
        if time_list[0] == previous_line_end_time:
            (your logic)
        # Update value of previous line
        previous_line_end_time = time_list[1]

If you need a value inside a for loop that depends on previous interaction you should store the value in a variable declared outside your for loop.

Upvotes: 1

Related Questions