Amazon Lex本身不提供翻译功能,但可以结合Amazon Translate实现翻译回复的功能。以下是使用AWS SDK for Python (boto3)实现在AWS Lambda中将用户输入进行翻译并回复用户的示例代码:
import boto3
import json
translate = boto3.client(service_name='translate', region_name='us-east-1', use_ssl=True)
def lambda_handler(event, context):
try:
user_input = event['currentIntent']['inputTranscript']
# 翻译为德语
response = translate.translate_text(Text=user_input, SourceLanguageCode="auto", TargetLanguageCode="de")
translated_response = response.get('TranslatedText')
# 构建回复
response = {
"sessionAttributes": event['sessionAttributes'],
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": translated_response
}
}
}
return response
except Exception as e:
print(e)
raise e
在以上示例代码中,我们使用AWS SDK for Python中的boto3模块调用Amazon Translate的API将用户输入翻译为德语。最后,我们将翻译后的文本作为回复返回给用户。根据需要,您可以修改源代码以实现其他语言的翻译。
上一篇:AmazonLex能否翻译回复?