文本翻译
引导式阅读
Python
文本翻译
作者
C***
上架时间
2023-11-13 06:48:18

功能介绍

文本翻译,将用户输入原始语种的文本转换为目标语种的文本。

前提条件

1、已注册华为云,并完成实名认证 。

2、已完成自然语言处理服务申请,具体请参考 申请服务

3、已获取自然语言处理服务对应区域终端节点地址,具体请参考 地区和终端节点

4、已获取自然语言处理服务对应区域的项目ID,请在华为云控制台“我的凭证 > API凭证”页面上查看项目ID。具体请参见 API凭证

5、已获取华为云帐号对应的有效AK、SK,具体请参见 如何获取访问密钥AK/SK

6、已具备开发环境 ,支持Python 3及其以上版本。

开始使用

from huaweicloudsdkcore.auth.credentials import BasicCredentials from huaweicloudsdkcore.exceptions.exceptions import ClientRequestException from huaweicloudsdkcore.exceptions.exceptions import ServerResponseException from huaweicloudsdknlp.v2.nlp_client import NlpClient from huaweicloudsdknlp.v2.model.run_text_translation_request import RunTextTranslationRequest from huaweicloudsdknlp.v2.model.text_translation_req import TextTranslationReq import os class RunTextTranslation: def __init__(self): pass @staticmethod def main(args): """ 初始化认证信息,相关参数说明如下所示: - ak:华为云账号Access Key。 - sk:华为云账号Secret Access Key 。 """ # 认证用的ak和sk直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全; # 本示例以ak和sk保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。 ak = os.environ["HUAWEICLOUD_SDK_AK"] sk = os.environ["HUAWEICLOUD_SDK_SK"] project_id = "<YOUR PROJECT ID>" endpoint = "<APIG ENDPOINT>" auth = BasicCredentials( ak=ak, sk=sk, project_id=project_id ) client = NlpClient.new_builder() \ .with_credentials(credentials=auth) \ .with_endpoint(endpoint=endpoint) \ .build() try: # 构造请求参数 text_translation_req = TextTranslationReq() text_translation_req._from = "zh" text_translation_req.to = "en" text_translation_req.text = "<YOUR TEXT>" text_translation_req.scene = "common" run_text_translation_request = RunTextTranslationRequest() run_text_translation_request.body = text_translation_req # 接收响应参数 response = client.run_text_translation(run_text_translation_request) print(response) except ClientRequestException as e: print(str(e.status_code)) print(e) except ServerResponseException as e: print(str(e.status_code)) print(e.error_msg)

参考

更多信息请参考 自然语言处理服务文档

修订记录

发布日期 文档版本 修订说明
2022-7-26 1.0 文档首次发布