python3 調用百度翻譯API翻譯英文

  • 2020 年 1 月 12 日
  • 筆記

自行申請百度開發者帳號

import importlib,sys,urllib  importlib.reload(sys)  import urllib.request    import json                                                                     #導入json模組    import hashlib    import urllib  import random            def translate(inputFile, outputFile):      fin = open(inputFile, 'r',encoding='utf-8')                                              #以讀的方式打開輸入文件      fout = open(outputFile, 'w',encoding='utf-8')                                            #以寫的方式代開輸出文件      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:                                                    #按行讀入文件          line = eachLine.strip()                                         #去除每行首尾可能的空格等          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)                               #調用百度翻譯API進行批量翻譯                  print (myurl)                  resultJason = resultPage.read().decode('utf-8')                #取得翻譯的結果,翻譯的結果是json格式                resultJasons = resultPage.read()                print (resultJason)                  try:                 js = json.loads(resultJason)                           #將json格式的結果轉換成Python的字典結構                       print ('dst')                 dst = str(js["trans_result"][0]["dst"])                     #取得翻譯後的文本結果                 outStr = dst                 print (dst)                 if dst[0]                 outDst=dst.strip()+"n"                 fout.write(outDst)                                     #如果翻譯出錯,則輸出原來的文本                except Exception as e:                 fout.write("n")                 continue          else:              fout.write("n")                #fout.write(dst.strip().encode('utf-8'))              #將結果輸出        fin.close()      fout.close()    if __name__ == '__main__':      translate(sys.argv[1], sys.argv[2])                                   #通過獲得命令行參數獲得輸入輸出文件名來執行,方便