Python调用有道API实现翻译功能

# -*- coding:utf-8 -*-
import requests
from requests.exceptions import RequestException

def translate(str_org):
    data = {
        'doctype': 'json',
        'type': 'AUTO',
        'i': str_org
    }
    url = "http://fanyi.youdao.com/translate"
    try:
        r = requests.get(url, params=data)
        if r.status_code == 200:
            result = r.json()
            translate_result = result['translateResult'][0][0]["tgt"]
            print(translate_result)
    except RequestException:
        print('ERROR: Cannot get the translation')

def main():
    translate("Test")

if __name__ == '__main__':
    main()
posted @ 2020-11-22 00:44  DevBobcorn  阅读(134)  评论(0编辑  收藏  举报