简单实现Python调用有道API接口(最新的)


 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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM