python學習日記-百度翻譯GUI,python學習日記gui

來源:互聯網
上載者:User

python學習日記-百度翻譯GUI,python學習日記gui

 跟女朋友聊天的時候,女朋友抱怨每次翻譯都要開啟百度網頁上找,這讓我有了做一個小的翻譯介面的想法,搜尋百度翻譯居然發現其有API,正合我意,上百度翻譯開放平台註冊一個個人測試帳號就可以了,東拼西湊,做出了來一個小程式,代碼如下:

 1 # coding=utf-8 2 from Tkinter import * 3 import tkMessageBox 4 import urllib2 5 import hashlib 6 import json 7  8  9 trans_id = '*****************'    #提供百度翻譯的APP ID10 trans_password = '***********'    #提供密鑰11 phone_num = '************'    #要求是salt,其實電話號碼就行12 13 14 def count(word):15     c = 016     for i in word:17         c += 118     return c19 20 21 def md5hex(word):22     if isinstance(word, unicode):23         word = word.encode("utf-8")24     elif not isinstance(word, str):25         word = str(word)26     m = hashlib.md5()27     m.update(word)28     return m.hexdigest()29 30 31 def trans(word, fr='en', to='zh'):32     word_num = count(word)33     sign = md5hex(trans_id + word + phone_num + trans_password)34     api = 'http://api.fanyi.baidu.com/api/trans/vip/translate?q=' + word + '&from=' + 'en' + '&to=' + 'zh' + '&appid=20161120000032369&salt=' + phone_num + '&sign=' + sign35     trans_data = urllib2.urlopen(api).read()36     trans_data = json.loads(trans_data)37     trans_data = trans_data['trans_result'][0]['dst']38     return trans_data39 40 41 class Application(Frame):42     def __init__(self, master=None):43         Frame.__init__(self, master, bd=30)44         self.pack()45         self.createWidgets()46 47     def createWidgets(self):48         self.nameInput = Entry(self)49         self.nameInput.pack()50         self.alertButton = Button(self, text='翻譯', command=self.hello)51         self.alertButton.pack()52 53     def hello(self):54         name = self.nameInput.get()55         result = trans(name)56         tkMessageBox.showinfo('翻譯結果', 'Result: %s' % result)57 58 app = Application()59 # 設定視窗標題:60 app.master.title('Translate')61 # 主訊息迴圈:62 app.mainloop()

測試回合結果還行,如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.