使用youtube_dl获取自动字幕并将其转换为文本稿件的python代码

8
自动提取的英语字幕从YouTube中提取,但不以可读形式包含信息,并且存在重复文本信息。
welcome<00:00:01.790><c> my</c><00:00:02.790><c> name</c><c.colorCCCCCC><00:00:02.820><c> is</c><00:00:03.210><c> Helga</c></c><c.colorE5E5E5><00:00:03.449><c> Vieira</c><00:00:03.929><c> and</c><00:00:04.080><c> this</c></c>

00:00:04.670 --> 00:00:04.680 align:start position:0%
welcome my name<c.colorCCCCCC> is Helga</c><c.colorE5E5E5> Vieira and this
 </c>

我的代码:

def captions_test02(url):
    ydl = youtube_dl.YoutubeDL({'writesubtitles': True, 'allsubtitles': True, 'writeautomaticsub': True})
    res = ydl.extract_info(url, download=False)
    if res['requested_subtitles'] and res['requested_subtitles']['en']:
        print('Grabbing vtt file from ' + res['requested_subtitles']['en']['url'])
        response = requests.get(res['requested_subtitles']['en']['url'], stream=True)
        f1 = open("testfile01.txt", "w")
        f1.write(response.text)
        f1.close()
        if len(res['subtitles']) > 0:
            print('manual captions')
        else:
            print('automatic_captions')
    else:
        print('Youtube Video does not have any english captions')

if __name__ == '__main__':
    captions_test02("https://www.youtube.com/watch?v=tCTqNZW0wIk&t=2s")

有没有什么建议可以得到一个合适的文本转录?起点:https://shkspr.mobi/blog/2018/09/convert-webvtt-to-a-transcript-using-python/


你有什么问题或者卡在哪里了吗?有具体的错误吗? - Pedro Lobito
感谢您的快速帮助,我正在寻找获取漂亮的文字转录的可能性。起点是https://shkspr.mobi/blog/2018/09/convert-webvtt-to-a-transcript-using-python/,但不幸的是没有任何标点符号。 - wuz
1个回答

6

为了消除时间戳并获得更好的转录,您可以使用正则表达式:

def captions_test02(url):
    ydl = youtube_dl.YoutubeDL({'writesubtitles': True, 'allsubtitles': True, 'writeautomaticsub': True})
    res = ydl.extract_info(url, download=False)
    if res['requested_subtitles'] and res['requested_subtitles']['en']:
        print('Grabbing vtt file from ' + res['requested_subtitles']['en']['url'])
        response = requests.get(res['requested_subtitles']['en']['url'], stream=True)
        f1 = open("testfile01.txt", "w")
        new = re.sub(r'\d{2}\W\d{2}\W\d{2}\W\d{3}\s\W{3}\s\d{2}\W\d{2}\W\d{2}\W\d{3}','',response.text)
        f1.write(new)
        f1.close()
        if len(res['subtitles']) > 0:
            print('manual captions')
        else:
            print('automatic_captions')
    else:
        print('Youtube Video does not have any english captions')

if __name__ == '__main__':
    captions_test02("https://www.youtube.com/watch?v=d1CDP6sMuLA") 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接