DEV Community

ClipDune
ClipDune

Posted on

Check subtitle line lengths in an SRT file with Python

A caption can fit on a landscape preview and still crowd a portrait video. Before editing the subtitles, use the character count to pick which lines are worth checking on a phone. This example uses 32 characters as a review threshold. Actual fit depends on your font and player.

Save this small sample as sample.srt:

1
00:00:00,000 --> 00:00:02,000
Meet me at the station.

2
00:00:02,000 --> 00:00:05,000
<i>We can record the second answer next to the window.</i>
Enter fullscreen mode Exit fullscreen mode

Save the script as check_captions.py. It reads the file locally and keeps the cue number and line number in each result. It removes the simple formatting tags in this sample before counting.

import re
from pathlib import Path


def long_lines(srt, limit=32):
    cues = re.split(r'\n[ \t]*\n', srt.replace('\r\n', '\n').strip())
    for cue in cues:
        lines = cue.splitlines()
        if len(lines) < 3 or not lines[0].isdigit() or '-->' not in lines[1]:
            continue
        for line_number, line in enumerate(lines[2:], 1):
            visible = re.sub(r'</?(?:b|i|u)>', '', line).strip()
            if len(visible) > limit:
                yield lines[0], line_number, len(visible), visible


if __name__ == '__main__':
    for cue, line, count, text in long_lines(Path('sample.srt').read_text(encoding='utf-8-sig')):
        print(f'Cue {cue}, line {line}: {count} characters — {text}')
Enter fullscreen mode Exit fullscreen mode

Run python3 check_captions.py. With the sample above the output is:

Cue 2, line 1: 51 characters — We can record the second answer next to the window.
Enter fullscreen mode Exit fullscreen mode

Review that cue at its actual timestamp first. One possible editorial split is “We can record the second answer” (31 characters) and “next to the window.” (19). Keep both lines in the same cue, then preview the portrait frame with the player’s real caption style. Check changes alongside the ClipDune portrait interview walkthrough.

This short example assumes ordinary numbered SRT cues. For complex styled subtitles, preserve layout and timing in your original subtitle editor. Code points and pixel widths measure different things, so use the report to choose what to preview.

The article was prepared with AI assistance. The sample and output above were run locally.

Top comments (0)