Skip to content

Commit 47aaa59

Browse files
committed
Merge pull request #54 from felagund/improve_cps
Make character_per_seconds correctly deal with tags and introduce text_w...
2 parents 99b3066 + 2e6663b commit 47aaa59

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

pysrt/srtitem.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from pysrt.srttime import SubRipTime
88
from pysrt.comparablemixin import ComparableMixin
99
from pysrt.compat import str, is_py2
10+
import re
1011

1112

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

40+
@property
41+
def text_without_tags(self):
42+
RE_TAG = re.compile(r'<[^>]*?>')
43+
return RE_TAG.sub('', self.text)
44+
3945
@property
4046
def characters_per_second(self):
41-
characters_count = len(self.text.replace('\n', ''))
47+
characters_count = len(self.text_without_tags.replace('\n', ''))
4248
try:
4349
return characters_count / (self.duration.ordinal / 1000.0)
4450
except ZeroDivisionError:

tests/test_srtitem.py

+37
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,43 @@ def test_zero_duration(self):
6464
self.item.start.shift(seconds = 20)
6565
self.assertEqual(self.item.characters_per_second, 0.0)
6666

67+
def test_tags(self):
68+
self.item.text = '<b>bold</b>, <i>italic</i>, <u>underlined</u>\n' + \
69+
'<font color="#ff0000">red text</font>' + \
70+
', <b>one,<i> two,<u> three</u></i></b>'
71+
self.assertEqual(self.item.characters_per_second, 2.45)
72+
73+
74+
class TestTagRemoval(unittest.TestCase):
75+
76+
def setUp(self):
77+
self.item = SubRipItem(1, text="Hello world !")
78+
self.item.shift(minutes=1)
79+
self.item.end.shift(seconds=20)
80+
81+
def test_italics_tag(self):
82+
self.item.text = "<i>Hello world !</i>"
83+
self.assertEqual(self.item.text_without_tags,'Hello world !')
84+
85+
def test_bold_tag(self):
86+
self.item.text = "<b>Hello world !</b>"
87+
self.assertEqual(self.item.text_without_tags,'Hello world !')
88+
89+
def test_underline_tag(self):
90+
self.item.text = "<u>Hello world !</u>"
91+
self.assertEqual(self.item.text_without_tags,'Hello world !')
92+
93+
def test_color_tag(self):
94+
self.item.text = '<font color="#ff0000">Hello world !</font>'
95+
self.assertEqual(self.item.text_without_tags,'Hello world !')
96+
97+
def test_all_tags(self):
98+
self.item.text = '<b>Bold</b>, <i>italic</i>, <u>underlined</u>\n' + \
99+
'<font color="#ff0000">red text</font>' + \
100+
', <b>one,<i> two,<u> three</u></i></b>.'
101+
self.assertEqual(self.item.text_without_tags,'Bold, italic, underlined' + \
102+
'\nred text, one, two, three.')
103+
67104

68105
class TestShifting(unittest.TestCase):
69106

0 commit comments

Comments
 (0)