最近在學習 Python 爬蟲,同時又在看英文版的小說《Don't Let Me Go》,小說里面好多單詞我都不認識,因此想到用 Python 寫一個翻譯小程序。
我用的是有道翻譯的 API 接口,url = ‘http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null’
代碼如下:
import json import requests def translation(word): """ 翻譯函數 :param word: :return: """ # 有道詞典 api url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null' # word 為需要翻譯的詞或者句子 data = { 'i':word, 'from':'AUTO', 'to':'Auto', 'doctype':'json', 'version':'2.1', 'keyfrom':'fanyi.web', 'action':'FY_BY_CLICKBUTTION', 'typoResult':'false' } response = requests.post(url,data=data) if response.status_code == 200: return response.text else: print("出錯了,請再試一次") return None def get_result(response): result = json.loads(response) print(result) print("輸入的詞/句為:%s" % result['translateResult'][0][0]['src']) print("翻譯的詞/句為:%s" % result['translateResult'][0][0]['tgt']) def main(): word = input("請輸入需要翻譯的詞或句子:") translate = translation(word) get_result(translate) if __name__ == "__main__": main()