171108 将Youtube自动翻译字幕转换成srt文件本地播放

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_33039859/article/details/78476993

Step1
打开YouTube的字幕显示,手动复制到txt文件保存
这里写图片描述

Step2
将保存的txt程序运用下面代码转换成需要的srt文件,拖拽至视频即可播放
这里写图片描述

# -*- coding: utf-8 -*-
"""
Created on Wed Nov  8 09:22:22 2017

@author: brucelau
"""
import re
#%% define a function to transform the date format
def time_format(cur):
    time = cur.split(':')
    hour = str(int(time[0])//60)
    minute = str(int(time[0])-int(time[0])//60*60)
    second = time[1]
    return hour+':'+minute+':'+second +',000'    

def txt2srt(filename):
    #%% generate new titles
    num = re.sub("\D", "", filename)
    f1 = open(filename)
    f2 = []
    lines = f1.readlines()
    for idx,time in enumerate(lines):
        if idx%2==0 & idx<len(lines)-4:
            cur = lines[idx]
            try:
                nex = lines[idx+2]
                t1 = time_format(cur).replace('\n','')
                t2 = time_format(nex).replace('\n','')
                t3 = t1+" --> "+t2
                f2.append(int(idx/2+1)) # order number
                f2.append(t3)   # time 
                f2.append(lines[idx+1]) # titles    
            except IndexError:
                continue
    f1.close()
    #%% save the new titles to .txt file
    srt_name = num + '. '+'Convex Optimization I Lecture '+num+'.srt'
    title3 = open(srt_name,'w') 
    title3.writelines(["%s\n" % item  for item in f2])

#%% genertate txt file for saving the titles
#for i in range(19):
#    title3 = open('title'+str(i+1)+'.txt','w') 

# 处理多个文件
for i in range(19):
    txtname = 'titles\\title'+str(i+1)+'.txt'
    txt2srt(txtname)
# 处理一个文件
txtname = 'RNN.txt'
txt2srt(txtname)

Step3
已整理好,可前往此处下载
http://download.csdn.net/download/qq_33039859/10109206

猜你喜欢

转载自blog.csdn.net/qq_33039859/article/details/78476993