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

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GuokLiu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值