跟女朋友聊天的时候,女朋友抱怨每次翻译都要打开百度网页上找,这让我有了做一个小的翻译界面的想法,搜索百度翻译居然发现其有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 ID 10 trans_password = ‘***********‘ #提供密钥 11 phone_num = ‘************‘ #要求是salt,其实电话号码就行 12 13 14 def count(word): 15 c = 0 16 for i in word: 17 c += 1 18 return c 19 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=‘ + sign 35 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_data 39 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()
测试运行结果还行,截图如下:
时间: 2024-10-25 02:13:52