Python 3 some code

Program that fixes srt delay according to a number of second to add or remove

Here the srt format :

1
00:00:04,584 --> 00:00:09,609
Hello you !
 
2
00:00:18,393 --> 00:00:23,064
Hello you too

Here the code to add/remove time :

import sys
import re
import traceback
from datetime import datetime, timedelta
 
 
def main():
    try:
        print(sys.getdefaultencoding())
        in_file = open("D:/foo.srt", mode="rt",
                       encoding='utf-8')
        out_file = open("D:/foo-out.srt", mode="at",
                        encoding='utf-8')
        # p_fint(inFile.read())
        lines = [line.strip('\n') for line in in_file]
 
        nb_line_processed = 0
        for line in lines:
            pattern = re.compile(r'(\d\d:\d\d:\d\d,\d\d\d)\s*-->\s*(\d\d:\d\d:\d\d,\d\d\d)')
            match = pattern.match(line)
            if match:
                first_and_second_time = match.groups()
                time_begin = compute_with_delta(first_and_second_time[0], 6.5)
                time_end = compute_with_delta(first_and_second_time[1], 6.5)
                out_file.write(f'{time_begin} --> {time_end}\n')
            else:
                #print(line)
                out_file.write(line + '\n')
            nb_line_processed += 1
        out_file.close()
        print("Done")
        print("nb line processed=", nb_line_processed)
    except Exception:
        print('Exception !')
        print('nb_line_processed=', nb_line_processed)
        print('nb_line_remaining=', len(lines) - nb_line_processed)
        print(traceback.format_exc())
 
 
def compute_with_delta(time, seconds):
    print("before", time)
    # class method : datetime.strptime()
    srt_time_pattern = '%H:%M:%S,%f'
    datetime_object: datetime = datetime.strptime(time, srt_time_pattern) + timedelta(seconds=seconds)
    time_fixed_str = datetime_object.strftime(srt_time_pattern)[:-3]
    try:
        j = 1
    except Exception:
        print("Exception case. time_fixed_str=", time_fixed_str)
        raise
 
    print("after", time_fixed_str)
    return time_fixed_str
 
 
if __name__ == '__main__':
    main()
Ce contenu a été publié dans Non classé. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *