alimt SDK 安裝
aliyun-python-sdk-alimt
阿裡雲機器翻譯Python使用Demo Code Sample
#!/usr/bin/env python
#coding=utf-8
from aliyunsdkcore.client import AcsClient
from aliyunsdkalimt.request.v20181012.TranslateGeneralRequest import TranslateGeneralRequest
client = AcsClient('LTAIOZZg********', 'v7CjUJCMk7j9aKduMA************', 'cn-hangzhou')
request = TranslateGeneralRequest()
request.set_accept_format('json')
request.set_FormatType("text")
request.set_SourceLanguage("zh")
request.set_TargetLanguage("en")
request.set_SourceText("北京歡迎你")
response = client.do_action_with_exception(request)
# python2: print(response)
print(str(response, encoding='utf-8'))
The Result
{"RequestId":"9DD4EC42-8977-4D2B-AA05-5D2BB27CC62D","Data":{"Translated":"Welcome to Beijing"},"Code":"200"}
core SDK
aliyun-python-sdk-core
SDK 安裝參考連結: 阿裡雲新版人臉識别 Python 使用示例教程
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
# DefaultProfile.getProfile的參數分别是地域,access_key_id, access_key_secret
client = AcsClient('***************', '***************', 'cn-hangzhou')
request = CommonRequest()
request.set_method("POST")
request.set_domain("mt.cn-hangzhou.aliyuncs.com")
request.set_action_name("TranslateGeneral")
request.set_version("2018-10-12")
request.set_accept_format('json')
request.add_body_params("FormatType", "text")
request.add_body_params("Scene", "general")
request.add_body_params("SourceLanguage", "zh")
request.add_body_params("SourceText", "中國人民共和國")
request.add_body_params("TargetLanguage", "en")
response = client.get_response(request)
response_str = str(response[2], 'utf-8') # bytes 轉 string
print(response_str) # 列印輸出結果
{"RequestId":"161E51D3-C3D2-49B4-B2B2-2CC9AC680567","Data":{"Translated":"People's Republic of China"},"Code":"200"}
參考連結
機器翻譯通用版調用指南 阿裡雲常見參數擷取位置