Advertisement
AngelSing0330

Line Length Limiter in Python

Mar 20th, 2023
840
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | Source Code | 0 0
  1. import re
  2. import codecs
  3.  
  4. def merge_subtitle_lines(input_file, output_file, max_characters):
  5.     with codecs.open(input_file, 'r', encoding='utf-8-sig') as f:
  6.         content = f.readlines()
  7.  
  8.     new_content = []
  9.     buffer = []
  10.     for line in content:
  11.         if re.match(r'^\d+$', line.strip()):
  12.             if buffer:
  13.                 merged_line = ' '.join(buffer)
  14.                 if len(merged_line) <= max_characters:
  15.                     new_content.append(merged_line + '\n')
  16.                 else:
  17.                     new_content.extend(buffer)
  18.                     new_content.append('\n')
  19.                 buffer = []
  20.             new_content.append(line)
  21.         elif re.match(r'^\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}$', line.strip()):
  22.             new_content.append(line)
  23.         elif line.strip():
  24.             if not buffer:
  25.                 buffer.append(line.strip())
  26.             elif len(' '.join(buffer + [line.strip()])) <= max_characters:
  27.                 buffer.append(line.strip())
  28.             else:
  29.                 new_content.extend(buffer)
  30.                 new_content.append('\n')
  31.                 buffer = [line.strip()]
  32.         else:
  33.             if buffer:
  34.                 new_content.extend(buffer)
  35.                 new_content.append('\n')
  36.             new_content.append(line)
  37.             buffer = []
  38.  
  39.     if buffer:
  40.         new_content.extend(buffer)
  41.         new_content.append('\n')
  42.  
  43.     with open(output_file, 'w', encoding='utf-8') as f:
  44.         f.writelines(new_content)
  45.  
  46. input_file = "E:/Desktop/testsub/16.Sub_ING.srt"
  47. output_file = "E:/Desktop/testsub/out/16.Sub_ING1.srt"
  48. max_characters = 56
  49.  
  50. merge_subtitle_lines(input_file, output_file, max_characters)
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement