python3 calls Baidu translation API to translate English subtitles

Apply for a Baidu developer account by yourself





import importlib,sys,urllib
importlib.reload(sys)
import urllib.request
  
import json #import json module  
                                                                           
import hashlib

import urllib
import random




  
def translate(inputFile, outputFile):  
    fin = open(inputFile, 'r',encoding='utf-8') #Open the input file for reading  
    fout = open(outputFile, 'w',encoding='utf-8') #Open the output file by writing  
    appid = '20170307000041649'
    secretKey = 'JcXq9a9QwvxN2l6AhIqH'

 

    myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    q = 'apple'
    fromLang = 'en'
    toLang = 'zh'
    salt = random.randint (32768, 65536)

   
    
      
    for eachLine in fin: #Read the file by line  
        line = eachLine.strip() #Remove possible spaces at the beginning and end of each line, etc.  
        if line:
          if line[0].isdigit():
              fout.write(line+"\n")
          else:
            
              sign = appid+line+str(salt)+secretKey
              sign = hashlib.md5(sign.encode()).hexdigest()
      
              myurl = myurl+'?appid='+appid+'&q='+urllib.parse.quote(line)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
              resultPage = urllib.request.urlopen(myurl) #Call Baidu Translate API for batch translation  
       
              print (myurl)
  
              resultJason = resultPage.read().decode('utf-8') #Get the translation result, the translation result is in json format
              resultJasons = resultPage.read()
              print (resultJason)
        
              try:
               js = json.loads(resultJason) #Convert the result in json format into a Python dictionary structure  
              
  
         
               print ('dst')
               dst = str(js["trans_result"][0]["dst"]) #Get the translated text result  
               outStr = dst  
               print (dst)
               if dst[0]
               outDst=dst.strip()+"\n"
               fout.write(outDst) #If the translation is wrong, output the original text  
              except Exception as e:
               fout.write("\n")
               continue
        else:
         
          fout.write("\n")

    
  
        #fout.write(dst.strip().encode('utf-8')) #Output the result  
        
    fin.close()  
    fout.close()  
  
if __name__ == '__main__':  
    translate(sys.argv[1], sys.argv[2]) #Execute by obtaining the input and output file names by obtaining command line parameters, which is convenient  


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325370347&siteId=291194637