|
发表于 2018-4-12 20:38:20
|
显示全部楼层
谢谢分享,你的程序经常出错,我改进了一下,短线了会自动重新启动
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 29 11:13:58 2017
@author: jerry-xu
"""
import requests
import json
import os
def translate(txt=''):
url = 'http://fy.iciba.com/ajax.php?a=fy'
req = requests.Session()
head = {'User-Agent': "Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0"}
data = {'f': 'auto', 't': 'auto', 'w': txt}
res = req.post(url, data=data, headers=head)
result = json.loads(res.text)
if result:
try:
out = result['content']['out']
except:
out = '\n'.join(result['content']['word_mean'])
try:
out = out.replace('<br/>', '\n')
except:
pass
else:
out = txt
return out
if __name__ == '__main__':
print('Srt Translation Program v0.1')
files = []
filepath = 'd:/1.srt' #input('Please input the srt file path \n >>>')
if filepath[-4:] != '.srt':
filelist = os.listdir(filepath)
for each in filelist:
if each[-4:] == '.srt':
files.append(filepath + '/' + each)
else:
files.append(filepath)
中文字幕文件=filepath[:-4]+'_cn'+filepath[-4:]
if os.path.exists(中文字幕文件):
print('中文字幕文件已存在')
else:
f=open(中文字幕文件,'w')
f.close()
while 1:
try:
with open(中文字幕文件) as f1:
lines = f1.readlines()
已翻译行数 = (len(lines))
with open(filepath) as f2, open(中文字幕文件, 'a') as f:
lines = f2.readlines()
总行数 = (len(lines))
if 总行数== 已翻译行数+2:
break
for line in lines[已翻译行数:]:
try:
print('Translating Line %d' % int(line))
f.write(line)
except:
if '-->' in line:
f.write(line)
elif len(line) == 0:
f.write('\n')
else:
f.write(translate(line))
f.write('\n')
f.flush()
except:
print('发生错误,重新启动')
import time
time.sleep(1)
print('翻译完成!') |
|