Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is some code I've been using to extract subtitles into CSV pairs for the purposes of language flashcards. The target encoding is hardcoded to iso-8859-1 and it requires both subtitle files to use the same timings, but otherwise it works just fine. Modified to handle multi-line sentences better. It drops some admittedly, but the flashcard qu…
#!/usr/bin/python
import unicodecsv
import argparse
import sys
import re
from pysrt import SubRipFile
# Determine which languages to import
parser = argparse.ArgumentParser()
parser.add_argument("source", help="source language file to parse")
parser.add_argument("target", help="target language file to parse")
args = parser.parse_args()
source = SubRipFile.open(args.source)
target = SubRipFile.open(args.target, encoding="iso-8859-1")
writer = unicodecsv.writer(sys.stdout, encoding="utf-8")
source_phrases = []
target_phrases = []
for entry in source:
source_phrase = entry.text
target_phrase = target.slice(ends_after=entry.start, starts_before=entry.end)[0].text
if re.search("^[a-z]", source_phrase) or (source_phrases and source_phrases[-1][-1][-1] == ","):
source_phrases[-1].append(source_phrase)
target_phrases[-1].append(target_phrase)
else:
source_phrases.append([source_phrase])
target_phrases.append([target_phrase])
for index in xrange(len(source_phrases)):
source_phrase = source_phrases[index]
target_phrase = target_phrases[index]
if re.search("^[A-Z]", source_phrase[0]) and re.search("[\?\.\!]$", source_phrase[-1]):
writer.writerow((
" ".join(source_phrase),
" ".join(target_phrase),
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.