Chatting with female friends, the girlfriend complained that every translation to open Baidu Web page to find, which let me have to do a small translation interface ideas, search Baidu translation actually found its API, is my intention, on the Baidu translation open platform registration of a personal test account can be, patchwork, made a small program, The code is as follows:
1 #Coding=utf-82 fromTkinterImport*3 ImportTkmessagebox4 ImportUrllib25 ImportHashlib6 ImportJSON7 8 9trans_id ='*****************' #provide the app ID of Baidu translatorTenTrans_password ='***********' #provide a key OnePhone_num ='************' #requirement is salt, actually phone number is OK A - - defcount (word): thec =0 - forIinchWord: -c + = 1 - returnC + - + defMd5hex (word): A ifisinstance (Word, Unicode): atWord = Word.encode ("Utf-8") - elif notisinstance (Word, str): -Word =STR (word) -m =hashlib.md5 () - m.update (Word) - returnm.hexdigest () in - to defTrans (word, fr='en', to='ZH'): +Word_num =count (Word) -Sign = Md5hex (trans_id + word + phone_num +Trans_password) theAPI ='http://api.fanyi.baidu.com/api/trans/vip/translate?q='+ Word +'&from='+'en'+'&to='+'ZH'+'&appid=20161120000032369&salt='+ Phone_num +'&sign='+ Sign *Trans_data =Urllib2.urlopen (API). Read () $Trans_data =json.loads (trans_data)Panax NotoginsengTrans_data = trans_data['Trans_result'][0]['DST'] - returnTrans_data the + A classApplication (Frame): the def __init__(Self, master=None): +Frame.__init__(Self, master, bd=30) - Self.pack () $ self.createwidgets () $ - defcreatewidgets (self): -Self.nameinput =Entry (self) the Self.nameInput.pack () -Self.alertbutton = Button (self, text='translation', command=Self.hello)Wuyi Self.alertButton.pack () the - defHello (self): WuName =Self.nameInput.get () -result =Trans (name) AboutTkmessagebox.showinfo ('Translation Results','Result:%s'%result) $ -App =application () - #To Set the window caption: -App.master.title (' Translate') A #main message loop: +App.mainloop ()
The test run result is OK, as follows:
Python Learning diary-Baidu translation GUI