AWS学习笔记-BOTO3 for Python:Translate

概述

Boto3 documentation for Amazon Translate可以帮助我们进行文本翻译。

本实验来自于https://learn-to-code.workshop.aws/

实验中,在标有client的部分中,告诉我们如何在程序中使用translate服务。

而AWS Translate的Boto3文档中,我们可以看到它支持不同的方法。

我们将在程序中使用translate_text()方法。在translate text方法中,文档从translate_text(**kwargs)开始,然后再往下有一个包含标题请求语法的部分。
请求语法如下所示:

response = client.translate_text(
    Text='string',
    TerminologyNames=[
        'string',
    ],
    SourceLanguageCode='string',
    TargetLanguageCode='string'
)

利用这些信息,我们可以构建python函数。
python函数中,:之前的()用于提供作为函数输入的参数。
Boto3中,使用方法(**kwargs)。这表示函数将接受任意数量的关键字参数。
translate_text()有三个 *[必需]*输入和一个可选输入。

  • Text [必需]
  • TerminologyNames-这是可选的,因为它没有按要求显示
  • SourceLanguageCode [必需]
  • TargetLanguageCode [必需]

所有这些都是类型字符串,TerminologyNames除外,TerminologyNames是一个包含类型字符串的逗号分隔值的列表。
现在,为了进一步简化我们的函数,我们将删除TerminologyNames,它不是必需的,并为我们的变量提供硬编码值。
链接文档中列出了SourceLanguageCode和TargetLanguageCode的可选项。

实验环境

采用Cloud9生成最简免费环境Linux t2,该环境已预装python
生成环境文件夹和安装boto3

zyi:~/environment $ python -m env_learn
/usr/bin/python3: No module named env_learn
zyi:~/environment $ python -m venv env_learn
zyi:~/environment $ pip install boto3
Defaulting to user installation because normal site-packages is not writeable
Collecting boto3
  Downloading boto3-1.19.0-py3-none-any.whl (131 kB)
     |████████████████████████████████| 131 kB 13.0 MB/s 
Collecting s3transfer<0.6.0,>=0.5.0
  Downloading s3transfer-0.5.0-py3-none-any.whl (79 kB)
     |████████████████████████████████| 79 kB 8.2 MB/s 
Collecting botocore<1.23.0,>=1.22.0
  Downloading botocore-1.22.0-py3-none-any.whl (8.0 MB)
     |████████████████████████████████| 8.0 MB 14.3 MB/s 
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.7/site-packages (from boto3) (0.10.0)
Requirement already satisfied: urllib3<1.27,>=1.25.4 in /usr/local/lib/python3.7/site-packages (from botocore<1.23.0,>=1.22.0->boto3) (1.26.7)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.7/site-packages (from botocore<1.23.0,>=1.22.0->boto3) (2.8.2)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/site-packages (from python-dateutil<3.0.0,>=2.1->botocore<1.23.0,>=1.22.0->boto3) (1.16.0)
Installing collected packages: botocore, s3transfer, boto3
Successfully installed boto3-1.19.0 botocore-1.22.0 s3transfer-0.5.0

实验步骤

Step 1 了解基本方法

我们将英语翻译为汉语,代码为en和zh。执行以下步骤:

  1. 创建一个.py的新文件,代码如下:

import boto3

client = boto3.client('translate')

def translate_text(): 
    response = client.translate_text(
        Text='Now that we have built our function and assigned values to our variables, we need to tell python to run the function and to output the response so we can see it. Do that now and our function is ready to run.', 
        SourceLanguageCode='en', 
        TargetLanguageCode='zh' 
    )
#### Add the new text below this line ####
    print(response) # this code is inside the function and will print the contents of the variable 'response' 

translate_text() # This line will call our function. Without it, python will not do anything.
  1. 解释
    首先,我们需要告诉python使用pip安装的boto3包。这是使用import-boto3语句完成的。
    其次,我们需要告诉python我们希望在boto3包中使用哪个特定的服务。这是通过client=boto3.client(‘translate’)完成的。

运行后得到结果:

{‘TranslatedText’: ‘现在我们已经构建了函数并为变量赋值,我们需要告诉 python 运行函数并输出响应,这样我们才能看到它。现在就这样做,我们的函数就可以运行了。’, ‘SourceLanguageCode’: ‘en’, ‘TargetLanguageCode’: ‘zh’, ‘ResponseMetadata’: {‘RequestId’: ‘5fbd6a5b-10c2-4362-b7eb-e686859c1627’, ‘HTTPStatusCode’: 200, ‘HTTPHeaders’: {‘x-amzn-requestid’: ‘5fbd6a5b-10c2-4362-b7eb-e686859c1627’, ‘cache-control’: ‘no-cache’, ‘content-type’: ‘application/x-amz-json-1.1’, ‘content-length’: ‘270’, ‘date’: ‘Thu, 21 Oct 2021 04:22:10 GMT’}, ‘RetryAttempts’: 0}}
Process exited with code: 0

返回结果是一个字典类型,我们可以在文档上得到其详细定义:

Return type
    dict

Returns
    Response Syntax

    {
        'TranslatedText': 'string',
        'SourceLanguageCode': 'string',
        'TargetLanguageCode': 'string',
        'AppliedTerminologies': [
            {
                'Name': 'string',
                'Terms': [
                    {
                        'SourceText': 'string',
                        'TargetText': 'string'
                    },
                ]
            },
        ]
    }

翻译的结果在TranslatedText,我们可以用print(response[“TranslatedText”])单独打印出。

Step 2 MAIN()函数

main()函数的作用是:设置python程序的入口点。
python程序将逐行运行,但在到达调用函数的行之前,它不会运行函数。
在前面的示例中,这是由line translate_text()调用的,该行调用translate_text()函数。

运行此代码时,解释器将定义一个名为_name_的特殊变量,并将“_main_”的值分配给此python文件中的代码。因此,python文件中的代码变成了_name_==“_main_”。

当我们使用import语句时,我们可以将代码从其他文件导入到python程序中。发生这种情况时,导入的代码被设置为模块名称的_name_值。
通过设置__name__==“__main__”,我们可以控制该文件中代码的执行顺序,告诉python运行该文件中名为_main_的代码,而不是从另一个文件导入的代码。这样可以避免代码可能运行导入的脚本,从而导致不必要的行为。

修改Step 1 的代码:

import boto3

client = boto3.client('translate')

def translate_text():
    response = client.translate_text(
        Text='We do this using an if statement. If statements are covered in more detail later. At this stage, all you need to understand is that it is telling the python interpreter that if the __name__ is equal to __main__ which relates to the code in this python file, then run the main() function.',
        SourceLanguageCode='en',
        TargetLanguageCode='zh-TW'
    )
    print(response) # this code is inside the function and will print the contents of the variable 'response'
    print("\n")
    print(response["TranslatedText"])
def main():
    translate_text()

if __name__=="__main__":
    main()

查看运行结果:

{‘TranslatedText’: ‘我們使用 if 語句來做到這一點。如果語句在稍後更詳細介紹。在這個階段,所有你需要了解的是,它告訴 python 解釋器,如果 name 等於 main 與此 python 文件中的代碼相關,然後運行 main()函數。’, ‘SourceLanguageCode’: ‘en’, ‘TargetLanguageCode’: ‘zh-TW’, ‘ResponseMetadata’: {‘RequestId’: ‘1536f78c-83e2-4a58-a0c3-01c61bbe6819’, ‘HTTPStatusCode’: 200, ‘HTTPHeaders’: {‘x-amzn-requestid’: ‘1536f78c-83e2-4a58-a0c3-01c61bbe6819’, ‘cache-control’: ‘no-cache’, ‘content-type’: ‘application/x-amz-json-1.1’, ‘content-length’: ‘340’, ‘date’: ‘Thu, 21 Oct 2021 07:46:11 GMT’}, ‘RetryAttempts’: 0}}
我們使用 if 語句來做到這一點。如果語句在稍後更詳細介紹。在這個階段,所有你需要了解的是,它告訴 python 解釋器,如果 name 等於 main 與此 python 文件中的代碼相關,然後運行 main()函數。

Step 3 传递参数

位置参数

我们将要使用的第一种方法称为位置参数positional arguments。顾名思义,参数传递给函数的顺序取决于括号()中的顺序。
修改以上函数,使位置参数:

import boto3

def translate_text(text, source_language_code, target_language_code): # we define the positional arguments in the ()
    client = boto3.client('translate')
    response = client.translate_text(
        Text=text, # we remove the hard coded value
        SourceLanguageCode=source_language_code, # we used the positional argument instead
        TargetLanguageCode=target_language_code
    )
    print(response) 
    print("\n")
    print(response["TranslatedText"])
def main():
    translate_text('Python substituted the actual values we provided when we called the function for the positional arguments and passed them to the parameters.','en','zh') # we provide the value for the arguments when we call the function in the correct positional order.

if __name__=="__main__":
    main()
  • 以上的代码中,我们删除了硬编码的参数值,并将其替换为参数名称:
    。 text
    。 source_language_code
    。 target_language_code.

  • 我们按照括号()之间的参数顺序将参数名称定义为输入。

  • 调用函数时,我们在顺序的位置使用了实际值。

查看运行结果:

{‘TranslatedText’: ‘Python 替换了我们在调用函数时提供的实际值作为位置参数并将它们传递给参数。’, ‘SourceLanguageCode’: ‘en’, ‘TargetLanguageCode’: ‘zh’, ‘ResponseMetadata’: {‘RequestId’: ‘e2f7bd3d-8541-4643-8fca-398d68ab5638’, ‘HTTPStatusCode’: 200, ‘HTTPHeaders’: {‘x-amzn-requestid’: ‘e2f7bd3d-8541-4643-8fca-398d68ab5638’, ‘cache-control’: ‘no-cache’, ‘content-type’: ‘application/x-amz-json-1.1’, ‘content-length’: ‘179’, ‘date’: ‘Thu, 21 Oct 2021 06:59:36 GMT’}, ‘RetryAttempts’: 0}}
Python 替换了我们在调用函数时提供的实际值作为位置参数并将它们传递给参数

关键字参数

关键字参数是传递给函数的 name-vlaue对。以下是一些优势:

  • 如果与位置参数一起传递的值错误,则会出现错误或意外行为。关键字参数可以按任意顺序传递。
  • 与**一起使用时,我们可以传递任意数量的关键字参数。
  • 可以减少代码中的行数。

对上面的代码进行修改:

import boto3

def translate_text(**kwargs): 
    client = boto3.client('translate')
    response = client.translate_text(**kwargs)
    print(response) 

def main():
    translate_text(Text='We replaced the positional arguments with keyword arguments. This is done using the **kwargs.We removed all the parameters such as Text=text which shortens our code and replaced it with response = client.translate_text(**kwargs).',SourceLanguageCode='en',TargetLanguageCode='zh')

if __name__=="__main__":
    main()
  • 我们用关键字参数替换了位置参数。这是使用**kwargs完成的。
  • 我们删除了所有参数,如Text=text,它缩短了代码,并将其替换为response=client.translate_Text(**kwargs)。
  • 我们在使用语法文本调用函数时定义了关键字参数Text=“We replaced the positional…”。

输出结果:

{‘TranslatedText’: ‘我们用关键字参数替换了位置参数。这是使用 **kwargs.we 删除了所有参数,例如 text=text,这会缩短我们的代码,并将其替换为 response = client.translate_text (**kwargs)。’, ‘SourceLanguageCode’: ‘en’, ‘TargetLanguageCode’: ‘zh’, ‘ResponseMetadata’: {‘RequestId’: ‘7c310ebb-9529-4401-8811-c2c487c3608c’, ‘HTTPStatusCode’: 200, ‘HTTPHeaders’: {‘x-amzn-requestid’: ‘7c310ebb-9529-4401-8811-c2c487c3608c’, ‘cache-control’: ‘no-cache’, ‘content-type’: ‘application/x-amz-json-1.1’, ‘content-length’: ‘284’, ‘date’: ‘Thu, 21 Oct 2021 07:47:53 GMT’}, ‘RetryAttempts’: 0}}

上面的代码使用语法 key=value定义关键字参数。
AWS通常以字典“key”:“value”格式返回信息。我们可以在函数中轻松地将它们用作关键字值。
接下来,修改调用函数的方式。将语法从key=value更改为“key”:“value”

import boto3

def translate_text(**kwargs): 
    client = boto3.client('translate')
    response = client.translate_text(**kwargs)
    print(response) 

### Change below this line only ###

kwargs={
    "Text":"In the last example, we defined keyword arguments using the syntax key=value. In the dictionaries part of the workshop we learned that dictionaries use a very similar format of key:value",
    "SourceLanguageCode":"en",
    "TargetLanguageCode":"zh"
    }

def main():
    translate_text(**kwargs)

if __name__=="__main__":
    main()
  • 我们定义了一个名为kwargs的变量,该变量包含一个key:value对字典。
  • 调用函数时,我们用**kwargs替换了关键字参数。**告诉python它是任意数量的参数,kwargs是我们定义的函数名。
  • 我们将每个键:值对放在单独的行上,以便阅读。

输出结果:

{‘TranslatedText’: ‘在最后一个示例中,我们使用语法 key=value 定义了关键字参数。在研讨会的词典部分,我们了解到字典使用了非常相似的 key: value 格式’, ‘SourceLanguageCode’: ‘en’, ‘TargetLanguageCode’: ‘zh’, ‘ResponseMetadata’: {‘RequestId’: ‘f3825202-513a-4fa5-a50c-319c6d3d0c55’, ‘HTTPStatusCode’: 200, ‘HTTPHeaders’: {‘x-amzn-requestid’: ‘f3825202-513a-4fa5-a50c-319c6d3d0c55’, ‘cache-control’: ‘no-cache’, ‘content-type’: ‘application/x-amz-json-1.1’, ‘content-length’: ‘249’, ‘date’: ‘Thu, 21 Oct 2021 07:18:28 GMT’}, ‘RetryAttempts’: 0}}

Over

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值