Step By Step
1.创建阿里云账号并开通机器翻译服务,具体可参考https://help.aliyun.com/document_detail/310982.html;
2.获取阿里云账号的AccessKey ID 和AccessKey Secret(可通过菜单栏右上角控制台进入,再点击个人头像,进入Accesskey管理即可查看)如下图:
3.添加python依赖
pip install aliyun-python-sdk-alimt==3.1.1
4. Python code
#!/usr/bin/env python
#coding=utf-8
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkalimt.request.v20181012.TranslateGeneralRequest import TranslateGeneralRequest
credentials = AccessKeyCredential('ak', 'sk')
# use STS Token
# credentials = StsTokenCredential('<your-access-key-id>', '<your-access-key-secret>', '<your-sts-token>')
client = AcsClient(region_id='cn-shanghai', credential=credentials)
request = TranslateGeneralRequest()
request.set_accept_format('json')
request.set_FormatType("text")
request.set_SourceLanguage("zh")
request.set_TargetLanguage("en")
request.set_SourceText("长亭外,古道边")
request.set_Scene("general")
response = client.do_action_with_exception(request)
# python2: print(response)
print(str(response, encoding='utf-8'))
5.运行结果
{"RequestId":"C4964FB7-D85E-5134-A6D6-AE3599B99823","Data":{"WordCount":"7","Translated":"Outside the long pavilion, beside the ancient road"},"Code":"200"}