srt字幕翻译
需要把字幕名改成i.txt
有有道和谷歌
代码:
import json import requests import re import os import sys from GoogleFreeTrans import Translator def google(ttt): translator = Translator.translator(src='auto', dest='zh-CN') return translator.translate(ttt) num=392 def translator(str): """ input : str 需要翻译的字符串 output:translation 翻译后的字符串 有每小时1000次访问的限制 """ global num; num=num+1 # API url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null' # 传输的参数, i为要翻译的内容 key = { 'type': "AUTO", 'i': str, "doctype": "json", "version": "2.1", "keyfrom": "fanyi.web", "ue": "UTF-8", "action": "FY_BY_CLICKBUTTON", "typoResult": "true" } # key 这个字典为发送给有道词典服务器的内容 response = requests.post(url, data=key) # 判断服务器是否相应成功 if response.status_code == 200: # 通过 json.loads 把返回的结果加载成 json 格式 result = json.loads(response.text) translation = result['translateResult'][0][0]['tgt'] return translation else: print("有道词典调用失败") # 相应失败就返回空 return None f = open("i.txt","r", encoding='UTF-8') txtstr = f.read() #将txt文件的所有内容读入到字符串txtstr中 f.close() list = txtstr.split('\n') print(list) q=input("选择翻译平台:1.有道 2.谷歌") q=int(q) j=0 for uchar in list: if (uchar >= u'\u0041' and uchar<=u'\u005a') or (uchar >= u'\u0061' and uchar<=u'\u007a'): if q==1: china=translator(uchar) elif q==2: china=google(uchar) list[j]=china print(china) j=j+1 txt="" for i in list: txt=txt+'\n'+i print(txt) f = open("china.txt","x") with open('china.txt','w', encoding='UTF-8') as f: #设置文件对象 f.write(txt)