如何在python項(xiàng)目中調(diào)用有道翻譯?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
代碼
import json import requests # 翻譯函數(shù),word 需要翻譯的內(nèi)容 def translate(word): # 有道詞典 api url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null' # 傳輸?shù)膮?shù),其中 i 為需要翻譯的內(nèi)容 key = { 'type': "AUTO", 'i': word, "doctype": "json", "version": "2.1", "keyfrom": "fanyi.web", "ue": "UTF-8", "action": "FY_BY_CLICKBUTTON", "typoResult": "true" } # key 這個(gè)字典為發(fā)送給有道詞典服務(wù)器的內(nèi)容 response = requests.post(url, data=key) # 判斷服務(wù)器是否相應(yīng)成功 if response.status_code == 200: # 然后相應(yīng)的結(jié)果 return response.text else: print("有道詞典調(diào)用失敗") # 相應(yīng)失敗就返回空 return None def get_reuslt(repsonse): # 通過(guò) json.loads 把返回的結(jié)果加載成 json 格式 result = json.loads(repsonse) return result['translateResult'][0][0]['tgt'] def main(err): word = err list_trans = translate(word) return get_reuslt(list_trans) print(main('魚(yú)')) """ """