本文主要是介绍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_modelsACCESS_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 + pathparams = {'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 openaiopenai.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")
这篇关于Python调用各大机器翻译其中阿里云、微软、ChatGPT的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!