本文整理汇总了Python中babelsubs.storage.SubtitleSet.append_subtitle方法的典型用法代码示例。如果您正苦于以下问题:Python SubtitleSet.append_subtitle方法的具体用法?Python SubtitleSet.append_subtitle怎么用?Python SubtitleSet.append_subtitle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类babelsubs.storage.SubtitleSet
的用法示例。
在下文中一共展示了SubtitleSet.append_subtitle方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: JSONParser
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
class JSONParser(BaseTextParser):
file_type = 'json'
def __init__(self, input_string, pattern, language=None, flags=[], eager_parse=True):
self.input_string = input_string
self.pattern = pattern
self.language = language
super(JSONParser, self).__init__(input_string, pattern, language=language,
flags=[], eager_parse=eager_parse)
def to_internal(self):
if not hasattr(self, 'sub_set'):
self.sub_set = SubtitleSet(self.language)
try:
data = json.loads(self.input_string)
except ValueError:
raise SubtitleParserError("Invalid JSON data provided.")
# Sort by the ``position`` key
data = sorted(data, key=lambda k: k['position'])
for sub in data:
self.sub_set.append_subtitle(sub['start'], sub['end'],
sub['text'])
return self.sub_set
示例2: YoutubeParser
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
class YoutubeParser(BaseTextParser):
file_type = 'youtube'
def __init__(self, input_string, language_code):
self.language_code = language_code
self._pattern = None
self.input_string = input_string
self.language = language_code
def __iter__(self):
if not hasattr(self, 'sub_set'):
self.to_internal()
for sub in self.sub_set:
yield sub
def to_internal(self):
if not hasattr(self, 'sub_set'):
try:
self.sub_set = SubtitleSet(self.language)
xml = etree.fromstring(self.input_string.encode('utf-8'))
has_subs = False
total_items = len(xml)
for i,item in enumerate(xml):
duration = 0
start = int(float(item.get('start')) * 1000)
if hasattr(item, 'duration'):
duration = int(float(item.get('dur', 0)) * 1000)
elif i+1 < total_items:
# youtube sometimes omits the duration attribute
# in this case we're displaying until the next sub
# starts
next_item = xml[i+1]
duration = int(float(next_item.get('start')) * 1000) - start
else:
# hardcode the last sub duration at 3 seconds
duration = 3000
end = start + duration
text = item.text and unescape_html(item.text) or u''
self.sub_set.append_subtitle(start, end, text)
has_subs = True
if not has_subs:
raise ValueError("No subs")
except Exception as e:
raise SubtitleParserError(original_error=e)
return self.sub_set
示例3: test_unsynced_generator
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
def test_unsynced_generator(self):
subs = SubtitleSet('en')
for x in xrange(0,5):
subs.append_subtitle(None, None,"%s" % x)
output = unicode(SBVGenerator(subs))
parsed = SBVParser(output,'en')
internal = parsed.to_internal()
subs = [x for x in internal.subtitle_items()]
self.assertEqual(len(internal), 5)
for i,sub in enumerate(subs):
self.assertEqual(sub[0], None )
self.assertEqual(sub[1], None )
generated = SBVGenerator(internal)
self.assertEqual(generated.format_time(None), u'9:59:59.990')
self.assertIn(u'''9:59:59.990,9:59:59.990\r\n0\r\n\r\n9:59:59.990,9:59:59.990\r\n1\r\n\r\n9:59:59.990,9:59:59.990\r\n2\r\n\r\n9:59:59.990,9:59:59.990\r\n3\r\n\r\n9:59:59.990,9:59:59.990\r\n4\r\n''',
unicode(generated))
示例4: test_unsynced_generator
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
def test_unsynced_generator(self):
subs = SubtitleSet('en')
for x in xrange(0,5):
subs.append_subtitle(None, None,"%s" % x)
output = unicode(DFXPGenerator(subs))
parsed = DFXPParser(output, 'en')
internal = parsed.to_internal()
subs = [x for x in internal.subtitle_items()]
self.assertEqual(len(internal), 5)
for i,sub in enumerate(subs):
self.assertIsNone(sub[0])
self.assertIsNone(sub[1])
self.assertEqual(sub[2], str(i))
for node in internal.get_subtitles():
self.assertIsNone(get_attr(node, 'begin'))
self.assertIsNone(get_attr(node, 'end'))
示例5: test_unsynced_generator
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
def test_unsynced_generator(self):
subs = SubtitleSet("en")
for x in xrange(0, 5):
subs.append_subtitle(None, None, "%s" % x)
output = unicode(SBVGenerator(subs, language="en"))
parsed = SBVParser(output, "en")
internal = parsed.to_internal()
subs = [x for x in internal.subtitle_items()]
self.assertEqual(len(internal), 5)
for i, sub in enumerate(subs):
self.assertEqual(sub[0], None)
self.assertEqual(sub[1], None)
generated = SBVGenerator(internal)
self.assertEqual(generated.format_time(None), u"9:59:59.000")
self.assertIn(
u"""9:59:59.000,9:59:59.000\r\n0\r\n\r\n9:59:59.000,9:59:59.000\r\n1\r\n\r\n9:59:59.000,9:59:59.000\r\n2\r\n\r\n9:59:59.000,9:59:59.000\r\n3\r\n\r\n9:59:59.000,9:59:59.000\r\n4\r\n""",
unicode(generated),
)
示例6: TXTParser
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
class TXTParser(BaseTextParser):
file_type = 'txt'
_linebreak_re = re.compile(r"\n\n|\r\n\r\n|\r\r")
def __init__(self, input_string, language=None, linebreak_re=_linebreak_re, eager_parse=True):
self.language = language
self.input_string = linebreak_re.split(input_string)
if eager_parse:
self.to_internal()
def __len__(self):
return len(self.input_string)
def __nonzero__(self):
return bool(self.input_string)
def _result_iter(self):
for item in self.input_string:
output = {}
output['start'] = None
output['end'] = None
output['text'] = utils.strip_tags(item)
yield output
def to_internal(self):
if not hasattr(self, 'sub_set'):
self.sub_set = SubtitleSet(self.language)
valid = False
for item in self._result_iter():
item['text'] = item['text'].replace("\n", '<br/>')
if not valid and ''.join(item['text'].split()):
valid = True
self.sub_set.append_subtitle(item['start'], item['end'],
item['text'], escape=False)
if not valid:
raise SubtitleParserError("No subs")
return self.sub_set
示例7: test_dfxp_merge
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
def test_dfxp_merge(self):
en_subs = SubtitleSet('en')
es_subs = SubtitleSet('es')
en_subs.append_subtitle(1000, 1500, 'content')
es_subs.append_subtitle(1000, 1500, 'spanish content')
result = self.loader.dfxp_merge([en_subs, es_subs])
utils.assert_long_text_equal(result, """\
<tt xmlns:tts="http://www.w3.org/ns/ttml#styling" xmlns:ttp="http://www.w3.org/ns/ttml#parameter" xmlns:ttm="http://www.w3.org/ns/ttml#metadata" xmlns="http://www.w3.org/ns/ttml" xml:lang="">
<head>
<metadata>
<ttm:title></ttm:title>
<ttm:description></ttm:description>
<ttm:copyright/>
</metadata>
<styling>
<style xml:id="test-style" tts:color="white" tts:fontSize="18px"/>
</styling>
<layout>
<region xml:id="bottom" style="test-style" tts:origin="0 80%" tts:extent="100% 20%"/>
<region xml:id="top" style="test-style" tts:origin="0 0" tts:extent="100% 20%"/>
</layout>
</head>
<body region="bottom">
<div xml:lang="en">
<div>
<p begin="00:00:01.000" end="00:00:01.500">content</p>
</div>
</div>
<div xml:lang="es">
<div>
<p begin="00:00:01.000" end="00:00:01.500">spanish content</p>
</div>
</div>
</body>
</tt>
""")
示例8: BaseTextParser
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
class BaseTextParser(object):
def __init__(self, input_string, pattern, language=None, flags=[], eager_parse=True):
'''
If `eager_parse` is True will parse the subtitles right way, converting to our
internal storage format, else only if you call `to_internal` directly (or `to`).
Any errors during parsing will be of SubtitleParserError.
Note that a file with no valid subs will be an error.
'''
self.input_string = input_string
self.pattern = pattern
self.language = language
self._pattern = re.compile(pattern, *flags)
if eager_parse:
self.to_internal()
def __iter__(self):
return self._result_iter()
def __len__(self):
return len(self._pattern.findall(self.input_string))
def __nonzero__(self):
return bool(self._pattern.search(self.input_string))
def _result_iter(self):
"""
Should iterate over items like this:
{
'start': ...,
'end': ...,
'text': ...
}
start_time and end_time in seconds. If it is not defined use -1.
"""
for item in self._matches:
yield self._get_data(item.groupdict())
def _get_data(self, match):
return match
def _get_matches(self):
return self._pattern.finditer(self.input_string)
def __unicode__(self):
return self.to(self.file_type)
@classmethod
def parse(cls, input_string, language=None):
return cls(input_string, language)
def to(self, type):
from babelsubs import to
if isinstance(type, list):
type = type[0]
return to(self.to_internal(), type, language=self.language)
def to_internal(self):
if not hasattr(self, 'sub_set'):
match = None
try:
self.sub_set = SubtitleSet(self.language)
for match in self._matches:
item = self._get_data(match.groupdict())
# fix me: support markup
text = self.get_markup(item['text'])
self.sub_set.append_subtitle(item['start'], item['end'], text, escape=False)
if match is None:
raise ValueError("No subs found")
except Exception as e:
raise SubtitleParserError(original_error=e)
return self.sub_set
def get_markup(self, text):
return text
_matches = property(_get_matches)
示例9: DFXPMergeTest
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
class DFXPMergeTest(TestCase):
def setUp(self):
self.en_subs = SubtitleSet('en')
self.es_subs = SubtitleSet('es')
self.fr_subs = SubtitleSet('fr')
self.en_subs.append_subtitle(1000, 1500, 'content')
self.es_subs.append_subtitle(1000, 1500, 'spanish content')
self.es_subs.append_subtitle(2000, 2500, 'spanish content 2',
new_paragraph=True)
self.fr_subs.append_subtitle(1000, 1500, 'french content')
def test_dfxp_merge(self):
result = DFXPGenerator.merge_subtitles(
[self.en_subs, self.es_subs, self.fr_subs])
utils.assert_long_text_equal(result, """\
<tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling" xml:lang="">
<head>
<metadata xmlns:ttm="http://www.w3.org/ns/ttml#metadata">
<ttm:title/>
<ttm:description/>
<ttm:copyright/>
</metadata>
<styling xmlns:tts="http://www.w3.org/ns/ttml#styling">
<style xml:id="amara-style" tts:color="white" tts:fontFamily="proportionalSansSerif" tts:fontSize="18px" tts:textAlign="center"/>
</styling>
<layout xmlns:tts="http://www.w3.org/ns/ttml#styling">
<region xml:id="amara-subtitle-area" style="amara-style" tts:extent="560px 62px" tts:padding="5px 3px" tts:backgroundColor="black" tts:displayAlign="after"/>
</layout>
</head>
<body region="amara-subtitle-area">
<div xml:lang="en">
<div>
<p begin="00:00:01.000" end="00:00:01.500">content</p>
</div>
</div>
<div xml:lang="es">
<div>
<p begin="00:00:01.000" end="00:00:01.500">spanish content</p>
</div>
<div>
<p begin="00:00:02.000" end="00:00:02.500">spanish content 2</p>
</div>
</div>
<div xml:lang="fr">
<div>
<p begin="00:00:01.000" end="00:00:01.500">french content</p>
</div>
</div>
</body>
</tt>
""")
def test_merge_with_header(self):
initial_ttml = etree.fromstring("""\
<tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling">
<head>
<styling>
<style xml:id="style" tts:color="foo" tts:fontSize="bar" />
</styling>
<layout>
<region xml:id="region" style="style" tts:extent="foo" tts:origin="bar" />
</layout>
</head>
<body />
</tt>""")
result = DFXPGenerator.merge_subtitles(
[self.en_subs, self.es_subs, self.fr_subs],
initial_ttml=initial_ttml)
utils.assert_long_text_equal(result, """\
<tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling" xml:lang="">
<head>
<styling>
<style xml:id="style" tts:color="foo" tts:fontSize="bar"/>
</styling>
<layout>
<region xml:id="region" style="style" tts:extent="foo" tts:origin="bar"/>
</layout>
</head>
<body>
<div xml:lang="en">
<div>
<p begin="00:00:01.000" end="00:00:01.500">content</p>
</div>
</div>
<div xml:lang="es">
<div>
<p begin="00:00:01.000" end="00:00:01.500">spanish content</p>
</div>
<div>
<p begin="00:00:02.000" end="00:00:02.500">spanish content 2</p>
</div>
</div>
<div xml:lang="fr">
<div>
<p begin="00:00:01.000" end="00:00:01.500">french content</p>
</div>
#.........这里部分代码省略.........
示例10: test_regions
# 需要导入模块: from babelsubs.storage import SubtitleSet [as 别名]
# 或者: from babelsubs.storage.SubtitleSet import append_subtitle [as 别名]
def test_regions(self):
subs = SubtitleSet('en')
sub = subs.append_subtitle(0, 1000, "test", region="top")
generator = WEBVTTGenerator(subs)
self.assertEqual(generator.format_cue_header(subs.subtitle_items()[0]),
u'00:00:00.000 --> 00:00:01.000 line:1')