使用本程序的效果就像在网页中输入内容后得到翻译结果:https://fanyi.youdao.com/

代码:

import json
import requests


def translate(word):
    def get_response(word):
        # 有道词典 api
        url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
        # 传输的参数,其中 i 为需要翻译的内容
        key = {
            'type': "AUTO",
            'i': word,
            "doctype": "json",
            "version": "2.1",
            "keyfrom": "fanyi.web",
            "ue": "UTF-8",
            "action": "FY_BY_CLICKBUTTON",
            "typoResult": "true"
        }
        # key 这个字典为发送给有道词典服务器的内容
        response = requests.post(url, data=key)
        # 判断服务器是否相应成功
        if response.status_code == 200:
            # 然后相应的结果
            return response.text
        else:
            print("有道词典调用失败")
            # 相应失败就返回空
            return None

    response = get_response(word)
    if response:
        result = json.loads(response)
        return result['translateResult'][0][0]['src'], result['translateResult'][0][0]['tgt']
    else:
        return word, None


if __name__ == '__main__':
    src, tgt = translate('开玩笑啦')
    print(src) # 输入的数据:'开玩笑啦'
    print(tgt) # 翻译的结果:A joke!

注意:会根据输入的信息,默认为英译汉、汉译英

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐