1 # '''
2 # Created on 2018-5-26
3 #
4 # @author: yaoshuangqi
5 # '''
6 import urllib.request 7 import urllib.parse 8 import json 9
10 class YoudaoFanyi(): 11 """
12 有道詞典API 13 """
14 VERSION = 1.1
15 URL = 'http://fanyi.youdao.com/openapi.do'
16 KEY_FROM = 'Dic-EVE'
17 KEY = '975360059'
18 TYPE = 'data'
19 # 可選值xml, json
20 DOC_TYPE = 'json'
21 def translate(self, text): 22 """
23 翻譯方法,傳入要翻譯的文本,返回結果字典 24 """
25 # 參數
26 params = {'keyfrom': self.KEY_FROM, 'key': self.KEY, 'type': self.TYPE, 'doctype': self.DOC_TYPE, 'version': self.VERSION ,'q': text} 27 resp = urllib.request.urlopen(self.URL, urllib.parse.urlencode(params).encode(encoding='utf_8')) 28 data = resp.read().decode("utf_8") 29 print('有道API翻譯內容:%s'%data) 30 return json.loads(data) 31
32 def format_for_command(self, text): 33 """
34 為命令行格式化翻譯結果 35 """
36 data = main(text) 37 # TODO:格式化字符串
38 if data: 39 print('有道翻譯:') 40 print('\t原文本:', data.get('query', text)) 41 translation = data.get('translation',None) 42 explains = data['basic']['explains'] 43 if translation: 44 for t in translation: 45 print('\t翻 譯:', t) 46 if explains: 47 print('\t解釋:',explains) 48 else: 49 print('未找到該詞') 50
51 def main(text): 52 if text and text.strip() != '': 53 return YoudaoFanyi().translate(text) 54
55 if __name__ == '__main__': 56 while True: 57 content = input('請輸入翻譯內容:') 58 if content: 59 YoudaoFanyi().format_for_command(content) 60 else: 61 print('有道翻譯: \n\t提示:您已退出!!') 62 break
有道翻譯API鏈接:http://fanyi.youdao.com/openapi?path=data-mode