【问题标题】:Splitting subtitle files with dialogs to strings (or files) in Python在 Python 中将带有对话框的字幕文件拆分为字符串(或文件)
【发布时间】:2021-12-12 15:36:22
【问题描述】:

我有一组包含对话的字幕文件,如下所示:

1
00:00:02,460 --> 00:00:07,020
JOHN: Great.

2
00:00:07,020 --> 00:00:11,850
How are you today? 
JANE: Quite alright. 
JOHN: Perfect.

3
00:00:11,850 --> 00:00:17,230
Had a busy day?

4
00:00:17,230 --> 00:00:28,070
JANE: Not so much. And you?

5
00:00:28,070 --> 00:00:32,300
JOHN: Mine was okay too. Gimme a few extra minutes.

我想只提取,例如 JANE,然后两者都提取,并得到一个结果字符串或文件,如下所示:

Quite alright 
Not so much
And you

然后两个扬声器组合在一起,如下所示:

Great
How are you today
Quite alright
Perfect
Had a busy day
Not so much
And you
Mine was okay too
Gimme a few extra minutes

因此,结果是每行一个句子,并删除了标点符号(除了 ' 之外的所有符号,保留用于缩写;例如,don't)。

有效地,我已经设法清除 标点符号和数字/时间戳。我一直在使用RegEx(infile是输入文件;首先re.sub()是用来整理在interpunction后没有空格的实例):

for line in infile:
    if not line[0].isnumeric():
        line = re.sub('(?<=[,;:.!?])(?=[a-zA-Z])', r' ', line)
        lines += re.sub(r'[^a-zA-Z\'\ \n]+', r'', line)

遗憾的是,我还没有找到任何优雅的方法来调节和提取属于某个特定扬声器的线条。原则上,我希望能够选择是否将全部保存到同一个字符串/文件中,每个扬声器保存到一个单独的字符串/文件(或仅一个扬声器)。

【问题讨论】:

  • 这是特定文件的确切格式吗?将对话分解成“编号块”的规则是什么?如果你知道这些规则,问题就很简单了……
  • 嗨,Buzz Moschetti,是的,这是(所有文件的)确切格式,因为我已经复制了摘录。第一个数字只是字幕的顺序,下一行包含在屏幕上呈现该字幕的开始和结束。我真的不知道时间究竟是如何“决定”的。我想,当说话者改变时,或者在长时间的停顿之后,或者考虑到任何字幕只能在两行中包含这么多字符等这一事实(很像 Twitter)。

标签: python python-re subtitle


【解决方案1】:

你基本上只需要不断嗅探说话者的变化并建立一个很好的结构化数据数组:

    current_speaker = None
    dialogue = []
    while(True):
        the_line = fetchLine(fromWhever)
        if the_line is None:
            break

        if the_line == '':
            continue
        if the_line.isnumeric():
            fetchLine(fromWherever)  # Get the timeline that follows a block count                                       
            continue  # ignore it all for now                                                                   

        # Actual speaker line.                                                                                  
        m = re.search("^(\S+):", the_line)
        if m is not None:
            spk = m.groups()[0]

            current_speaker = spk
            the_line = the_line[len(spk)+2:] # remove name, colon, and 1 space                                  

        dialogue.append({"spk":current_speaker,"text":the_line})

    print(dialogue)

[{'spk': 'JOHN', 'text': 'Great.'}, {'spk': 'JOHN', 'text': 'How are you today? '}, {'spk': 'JANE', 'text': 'Quite alright. '}, {'spk': 'JOHN', 'text': 'Perfect.'}, {'spk': 'JOHN', 'text': 'Had a busy day?'}, {'spk': 'JANE', 'text': 'Not so much. And you?'}, {'spk': 'JOHN', 'text': 'Mine was okay too. Gimme a few extra minutes.'}]

在此之后,只需对数组进行后处理以将句子转换为更多条目或写入文件等即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    相关资源
    最近更新 更多