zoukankan      html  css  js  c++  java
  • 简单实现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('	原文本:', 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)
    46                 if explains:
    47                     print('	解释:',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('有道翻译: 
    	提示:您已退出!!')
    62             break
    有道翻译API链接:http://fanyi.youdao.com/openapi?path=data-mode

  • 相关阅读:
    day7
    11.3NOIP模拟赛
    codeforces 880E. Maximum Subsequence(折半搜索+双指针)
    11.2NOIP模拟赛
    bzoj1483: [HNOI2009]梦幻布丁(vector+启发式合并)
    day9
    codeforces 1006 F(折半搜索)
    codeforces 28D(dp)
    P2210 Haywire(A*)
    4800: [Ceoi2015]Ice Hockey World Championship(折半搜索)
  • 原文地址:https://www.cnblogs.com/ysq0908/p/9096707.html
Copyright © 2011-2022 走看看