Python调用各大机器翻译其中阿里云、微软、ChatGPT

一、Python调用阿里云机器翻译api

阿里云机器翻译api的调用比较繁琐,申请过程也较复杂,其翻译质量倒时一般,大家可以有选择地使用以下代码:

from alibabacloud_alimt20181012.client import Client as alimt20181012Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_alimt20181012 import models as alimt_20181012_models
from alibabacloud_tea_util import models as util_models

ACCESS_KEY_ID = 【Access_key_id>】#这里把尖括号里的 Acess_key_id和Acess_key_secret分别修改为自己申请的通用翻译api
ACCESS_KEY_SECRET = 【Access_key_secret】

def create_client(
    access_key_id: str,
    access_key_secret: str,
) -> alimt20181012Client:
    config = open_api_models.Config(
        access_key_id=access_key_id,
        access_key_secret=access_key_secret
    )
    config.endpoint = f'mt.cn-hangzhou.aliyuncs.com'
    return alimt20181012Client(config)
def translate(text):
    client = create_client(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
    translate_general_request = alimt_20181012_models.TranslateGeneralRequest(
        format_type='text',
        source_language='en',
        target_language='zh',
        source_text=text,
        scene='general'
    )
    runtime = util_models.RuntimeOptions()
    resp = client.translate_general_with_options(translate_general_request, runtime)
    return resp.body.data.__dict__['translated']
print(translate("Rome is not built in a day."))

二、Python调用微软机器翻译

微软机器翻译一般情况需要登记信用卡,但是它们提供的Azure for Students可以免费使用机器翻译API,而不用登记信用卡。官方提供的样例代码中有一些错误,修改完善后得出以下代码。主要修改的地方是key和location两个变量。

import requests, uuid, json

# Add your key and endpoint
key = "<Bing- Api-Key>"
endpoint = "https://api.cognitive.microsofttranslator.com"

# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
location = "global"

path = '/translate'
constructed_url = endpoint + path

params = {
    'api-version':'3.0',
    'from':'zh',
    'to':'ja'
}

headers = {
    'Ocp-Apim-Subscription-Key': key,
    # location required if you're using a multi-service or regional (not global) resource.
    'Ocp-Apim-Subscription-Region':location,
    'Content-type': 'application/json',
    'X-ClientTraceId': str(uuid.uuid4())
}

# You can pass more than one object in body.
body = [{
    'text': '我非常喜欢读书。'
}]

request = requests.post(constructed_url, params=params, headers=headers, json=body)

response = request.json()

#trans = json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': '))

print(body[0]['text'],response[0]['translations'][0]["text"],sep="\n")

三、利用ChatGPT来翻译

ChatGPT也可以用于翻译,只要我们给它发出指令即可。代码如下:

import openai

openai.api_base = "https://api.openai.com/v1"

openai.api_key = "YOUR_API_KEY"

model_engine_id = "text-davinci-003"

while True:
    prompt = input("Q:")
    completions = openai.Completion.create(
        engine=model_engine_id,
        prompt="Translate the following sentences into Chinese:"+prompt,
        max_tokens=800,
    )

    message = completions.choices[0].text.strip()

    print("A:",message,end="\n")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值