Skip to content

Commit

Permalink
Make character_per_seconds correctly deal with tags and introduce tex…
Browse files Browse the repository at this point in the history
…t_without_tags property
  • Loading branch information
felagund committed May 27, 2014
1 parent 99b3066 commit 2e6663b
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
8 changes: 7 additions & 1 deletion pysrt/srtitem.py
Expand Up @@ -7,6 +7,7 @@
from pysrt.srttime import SubRipTime
from pysrt.comparablemixin import ComparableMixin
from pysrt.compat import str, is_py2
import re


class SubRipItem(ComparableMixin):
Expand Down Expand Up @@ -36,9 +37,14 @@ def __init__(self, index=0, start=None, end=None, text='', position=''):
def duration(self):
return self.end - self.start

@property
def text_without_tags(self):
RE_TAG = re.compile(r'<[^>]*?>')
return RE_TAG.sub('', self.text)

@property
def characters_per_second(self):
characters_count = len(self.text.replace('\n', ''))
characters_count = len(self.text_without_tags.replace('\n', ''))
try:
return characters_count / (self.duration.ordinal / 1000.0)
except ZeroDivisionError:
Expand Down
37 changes: 37 additions & 0 deletions tests/test_srtitem.py
Expand Up @@ -64,6 +64,43 @@ def test_zero_duration(self):
self.item.start.shift(seconds = 20)
self.assertEqual(self.item.characters_per_second, 0.0)

def test_tags(self):
self.item.text = '<b>bold</b>, <i>italic</i>, <u>underlined</u>\n' + \
'<font color="#ff0000">red text</font>' + \
', <b>one,<i> two,<u> three</u></i></b>'
self.assertEqual(self.item.characters_per_second, 2.45)


class TestTagRemoval(unittest.TestCase):

def setUp(self):
self.item = SubRipItem(1, text="Hello world !")
self.item.shift(minutes=1)
self.item.end.shift(seconds=20)

def test_italics_tag(self):
self.item.text = "<i>Hello world !</i>"
self.assertEqual(self.item.text_without_tags,'Hello world !')

def test_bold_tag(self):
self.item.text = "<b>Hello world !</b>"
self.assertEqual(self.item.text_without_tags,'Hello world !')

def test_underline_tag(self):
self.item.text = "<u>Hello world !</u>"
self.assertEqual(self.item.text_without_tags,'Hello world !')

def test_color_tag(self):
self.item.text = '<font color="#ff0000">Hello world !</font>'
self.assertEqual(self.item.text_without_tags,'Hello world !')

def test_all_tags(self):
self.item.text = '<b>Bold</b>, <i>italic</i>, <u>underlined</u>\n' + \
'<font color="#ff0000">red text</font>' + \
', <b>one,<i> two,<u> three</u></i></b>.'
self.assertEqual(self.item.text_without_tags,'Bold, italic, underlined' + \
'\nred text, one, two, three.')


class TestShifting(unittest.TestCase):

Expand Down

0 comments on commit 2e6663b

Please sign in to comment.