使用python语言调用有道翻译接口实现中英互译

中英互译函数:

def translate(the_word):
    """中英互译函数."""
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
    key = {'type': "AUTO",
           'i': the_word,
           "doctype": "json",
           "version": "2.1",
           "keyfrom": "fanyi.web",
           "ue": "UTF-8",
           "action": "FY_BY_CLICKBUTTON",
           "typoResult": "true"}
    for _ in range(5):
        try:
            response = req.post(url, data=key)
            if response.status_code == 200:
                result = response.json()
                the_word = result['translateResult'][0][0]['tgt']
                return the_word
        except Exception as exception:
            print(f"ERROR !!! {exception}")
    return None

调用函数:

if __name__ == '__main__':
    word = 'i like apple'
    new_result = translate(word)
    print(new_result)

你可能感兴趣的:(python基础,开发语言,python)