1 #/usr/bin/env Python32 #Coding=utf83 4 """Baidu translation API function implementation function, this module is based on python3.x implementation, Gettransresult (q) parameter q is the content to be translated, the current function of the source language default English, the target language default Simplified Chinese"""5 6 7 Importhttp.client8 ImportHashlib9 ImportUrllibTen ImportRandom One ImportDemjson A - defGettransresult (q): - the """ - from the Baidu translation API to obtain the source language translation results of the implementation function. Get request string Construction Please refer to Baidu Translator Developer documentation - Fromlang&&tolang is the source language and target language, the default is English and Simplified Chinese, the latter can be dynamically passed on as function parameters according to demand. - """ + -AppID ='xxxxxxxxxxxx' #Developer ID +Secretkey ='xxxxxxxxxx' #Developer Key A at -HttpClient =None -Myurl ='/api/trans/vip/translate' - #q = ' Hello Baidu trans ' #要翻译的内容 -Fromlang ='en' #Source Language -Tolang ='ZH' #Target Language inSalt = Random.randint (32768, 65536)#Random number - toSign = appid+q+str (salt) +secretkey#a string that needs to generate a MD5 code + -M1 = Hashlib.md5 (Sign.encode (encoding='Utf-8')) theSign =m1.hexdigest () *Myurl = myurl+'? appid='+appid+'&q='+urllib.parse.quote (q) +'&from='+fromlang+'&to='+tolang+'&salt='+str (SALT) +'&sign='+sign#GET Request String $ Panax Notoginseng Try: -HttpClient = Http.client.HTTPConnection ('api.fanyi.baidu.com') theHttpclient.request ('GET', Myurl) + #response is the HttpResponse object AResponse = Httpclient.getresponse ()#Get return results theMresult = Demjson.decode (Response.read ())#JSON decoding + #print (mresult["Trans_result"][0]["DST"]) - returnmresult["Trans_result"][0]["DST"] $ $ exceptException as E: - Print(e) - finally: the ifhttpClient: - httpclient.close ()Wuyi the - if __name__=="__main__": Wu Print(Gettransresult ("Hello"))
Baidu Translation API