Skip to content

Commit

Permalink
Simplify Subtitle.to_srt
Browse files Browse the repository at this point in the history
  • Loading branch information
cdown committed Oct 18, 2015
1 parent 8db7c21 commit aca4b4a
Showing 1 changed file with 25 additions and 13 deletions.
38 changes: 25 additions & 13 deletions srt.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,26 +80,38 @@ def to_srt(self, strict=True):
SRT formatted subtitle block
:rtype: str
'''
output_content = self.content
output_proprietary = self.proprietary

if output_proprietary:
# output_proprietary is output directly next to the timestamp, so
# we need to add the space as a field delimiter.
output_proprietary = ' ' + output_proprietary

if strict:
content = '\n'.join(
# We can't use .splitlines() here since it does all sorts of
# stuff that we don't want with \x1{c..e}, etc
line for line in self.content.split('\n') if line
).strip('\n')
else:
content = self.content

if self.proprietary:
proprietary_output = ' ' + self.proprietary
else:
proprietary_output = ''
output_content = make_legal_content(output_content)

return '%d\n%s --> %s%s\n%s\n\n' % (
self.index, timedelta_to_srt_timestamp(self.start),
timedelta_to_srt_timestamp(self.end), proprietary_output, content,
timedelta_to_srt_timestamp(self.end), output_proprietary,
output_content,
)


def make_legal_content(content):
'''
Remove illegal content from a content block. Illegal content includes:
* Blank lines
* Starting or ending with a blank line
:param srt content: the content to make legal
'''
# We can't use content.splitlines() here since it does all sorts of stuff
# that we don't want with \x1{c..e}, etc
return '\n'.join(line for line in content.split('\n') if line)


def timedelta_to_srt_timestamp(timedelta_timestamp):
r'''
Convert a :py:class:`~datetime.timedelta` to an SRT timestamp.
Expand Down

0 comments on commit aca4b4a

Please sign in to comment.