python使用youtube_dl检索自动字幕并转换为字幕

时间:2018-12-06 20:47:01

标签: python youtube-dl

从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/

1 个答案:

答案 0 :(得分:0)

要消除时间戳并获得更好的成绩单,可以使用regex:

    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")