2020-07-26調(diào)用百度API應(yīng)用——小小翻譯器

? urllib是Python標(biāo)準(zhǔn)庫(kù)中最常用的python網(wǎng)頁(yè)訪問模塊,它可以讓用戶像訪問文本一樣讀取網(wǎng)頁(yè)的內(nèi)容

```

from tkinter import *

from urllib import request

from urllib import parse

import json

import hashlib

def translate_Word(en_str):

? ? URL = 'http://api.fanyi.baidu.com/api/trans/vip/translate'

? ? Form_Data = {}? ? ? #創(chuàng)建From_Data字典,存儲(chǔ)向服務(wù)器發(fā)送的Data

? ? Form_Data['from'] = 'en'? ? ? #譯前---英文

? ? Form_Data['to'] = 'zh'? ? ? ? #譯后---中文

? ? Form_Data['q'] = en_str

? ? Form_Data['appid'] = '2015063000000001'? ? #自己申請(qǐng)的app id

? ? Form_Data['salt'] = '1435660288'? ? ? ? ?

? ? Key = "12345678"? ? ? ? ? ? ? ? ? ? ? ? ? #平臺(tái)分配的密鑰

? ? m = Form_Data['appid'] + en_str + Form_Data['salt'] + Key

? ? m_MD5 = hashlib.md5(m.encode('utf8'))

? ? Form_Data['sign'] = m_MD5.hexdigest()


? ? data = parse.urlencode(Form_Data).encode('utf-8') #使用urlencode()方法轉(zhuǎn)換為標(biāo)準(zhǔn)格式


? ? response = request.urlopen(URL,data)

? ? html = response.read().decode('utf-8')? ? ? ? ? ? #讀取信息并解碼

? ? translate_results = json.loads(html)

? ? print(translate_results)

? ? translate_results = translate_results['trans_result'][0]['dst']? #找到翻譯結(jié)果

? ? print("翻譯的結(jié)果是:%s" % translate_results)

? ? return translate_results

def leftClick(event):

? ? en_str = Entry1.get()

? ? print(en_str)

? ? vText = translate_Word(en_str)

? ? Entry2.config(Entry2,text = vText)

? ? s.set("")

? ? Entry2.insert(0,vText)


def leftClick2(event):

? ? s.set("")

? ? Entry2.insert(0,"")


if __name__ == "__main__":

? ? root = Tk()

? ? root.title("單詞翻譯器")

? ? root['width'] = 250;root['height'] = 130

? ? Label(root,text = '輸入要翻譯的內(nèi)容:',width = 15).place(x = 1,y = 1)? ? #絕對(duì)坐標(biāo)

? ? Entry1 = Entry(root,width = 20)

? ? Entry1.place(x = 110,y = 1)

? ? Label(root,text = '翻譯的結(jié)果:',width = 18).place(x = 1,y = 20)

? ? s = StringVar()

? ? s.set("大家好,這是測(cè)試")

? ? Entry2 = Entry(root,width = 20,textvariable = s)

? ? Entry2.place(x = 110,y = 20)

? ? Button1 = Button(root,text = '翻譯',width = 8)

? ? Button1.place(x = 40,y = 80)

? ? Button2 = Button(root,text = '清空',width = 8)

? ? Button2.place(x = 110,y = 80)

? ? Button1.bind("<Button-1>",leftClick)

? ? Button2.bind("<Button-1>",leftClick2)

? ? root.mainloop()

```

結(jié)果:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容