#Author:Chenglong Qian #Copyright :Chenglong Qian import json import requests import re import os import sys num=392 def translator(str): """ input : str 需要翻译的字符串 output:translation 翻译后的字符串 有每小时1000次访问的限制 """ global num; num=num+1 print("Program has process %d times "%num) # 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) # print ("输入的词为:%s" % result['translateResult'][0][0]['src']) # print ("翻译结果为:%s" % result['translateResult'][0][0]['tgt']) translation = result['translateResult'][0][0]['tgt'] return translation else: print("有道词典调用失败") # 相应失败就返回空 return None def file_translator(file_name): file = os.listdir(file_name) for i in file: if i.endswith('.srt'): filepath = os.path.join(dir, i) name = i[:-4] with open(filepath) as f: with open(name + "-translate.srt", 'w', encoding='utf-8') as f_trans: content = f.readlines()#读取文件 transcontent = '' for i in content:#遍历每一行 pattern = r'.*?([>a-zA-Z].*?[a-zA-Z].*?) ' flag = re.search(pattern, i) if flag !=None: transcontent=translator(flag.string) transcontent=transcontent+r' ' f_trans.write(transcontent) f_trans.write(i) else: f_trans.write(i) dir=r'D:srt' def main(): global num if num<950: file_translator(dir) main()
https://blog.csdn.net/qq_36771895/article/details/90510742