调用百度云API机器翻译

新建Python文件,叫

复制代码
text_translator.py

输入

复制代码
import requests
import json

API_KEY = "glYiYVF2dSc7EQ8n78VDRCpa"  # 替换为自己的API Key
SECRET_KEY = "kUlhze8OQZ7xbVRp"  # 替换为自己的Secret Key


def main():
    # 选择翻译方向
    while True:
        direction = input("请选择翻译方向(输入1: 中译英,输入2: 英译中):").strip()
        if direction == '1':
            from_lang, to_lang = 'zh', 'en'
            break
        elif direction == '2':
            from_lang, to_lang = 'en', 'zh'
            break
        else:
            print("输入错误,请重新输入!")

    # 输入待翻译文本(支持多行输入)
    print("\n请输入需要翻译的文本(输入完成后请输入'END'并回车):")
    text_lines = []
    while True:
        line = input()
        if line.strip().upper() == 'END':
            break
        text_lines.append(line)
    original_text = '\n'.join(text_lines)

    if not original_text.strip():
        print("错误:输入的文本不能为空!")
        return

    # 调用翻译API
    try:
        url = f"https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token={get_access_token()}"

        payload = json.dumps({
            "from": from_lang,
            "to": to_lang,
            "q": original_text
        }, ensure_ascii=False)

        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }

        response = requests.post(url, headers=headers, data=payload.encode('utf-8'))
        response.raise_for_status()  # 检查HTTP状态码是否正常

        result = response.json()
        if 'error_code' in result:
            print(f"\n翻译失败!错误码:{result['error_code']},错误信息:{result['error_msg']}")
        else:
            translated_text = result['result']['trans_result'][0]['dst']
            print("\n翻译结果:")
            print(translated_text)

    except requests.exceptions.RequestException as e:
        print(f"\n网络请求异常:{str(e)}")
    except KeyError as e:
        print(f"\n解析结果失败,可能API返回格式变化:{str(e)}")
    except Exception as e:
        print(f"\n发生未知错误:{str(e)}")


def get_access_token():
    """获取API访问凭证"""
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": API_KEY,
        "client_secret": SECRET_KEY
    }
    try:
        response = requests.post(url, params=params)
        response.raise_for_status()
        return response.json().get("access_token")
    except Exception as e:
        print(f"获取access_token失败:{str(e)}")
        return None


if __name__ == '__main__':
    main()

运行结果如图

相关推荐
Evanfu02164 天前
商业短剧上传 AI 工具前,要检查哪些安全与删除规则?
自然语言处理·aigc·音视频·视频·机器翻译·自动翻译
SamChan905 天前
Python 处理小语种 PDF 的编码坑:重音字符、连字与 (cid:xx) 乱码的解决方案
python·ai·pdf·机器翻译
SamChan9010 天前
Python批量处理PDF踩坑实录:中文编码、字体内嵌、多栏排版与内存占用
python·单片机·ai·pdf·机器翻译
SamChan9012 天前
PDF翻译后的格式完整性校验:用Python自动比对译文与原文档的表格与段落结构
开发语言·python·ai·pdf·机器翻译
SamChan9012 天前
大文件多语言PDF翻译性能实测:300页文档的耗时、内存占用与失败率分析
python·ai·pdf·机器翻译
SamChan9014 天前
PDF多语言翻译的格式还原技术拆解:从版面分析到内容重排的工程实现
python·ai·pdf·机器翻译
台风护盾17 天前
视频怎么自动翻译成中文字幕?AI 视频翻译的三道坎和一条捷径
人工智能·机器翻译·音频处理·ai工具·视频翻译
极客猴子21 天前
iPhone免费版支持思维导图导出的会议APP推荐:导出能力对照
人工智能·智能手机·音视频·机器翻译
Eric.4624 天前
秋叶ComfyUI-AKI最新整合包|完整部署教程+核心指令手册
云计算·百度云·comfyui·ai漫剧
TAN-90°-24 天前
Deep Learning for Computer Vision——Attention and Transformers
人工智能·深度学习·神经网络·机器学习·计算机视觉·cnn·机器翻译