How to use Amazon Translate using AWS SDK for Python (Boto3)

2018.10.28

Amazon now supports translation between English and one of the following languages:

  • Arabic (ar)
  • Chinese (Simplified) (zh)
  • Chinese (Traditional) (zh-TW)
  • Czech (cs)
  • French (fr)
  • German (de)
  • Italian (it)
  • Japanese (ja)
  • Portuguese (pt)
  • Russian (ru)
  • Spanish (es)
  • Turkish (tr)

In this post, we will illustrate how to use the translate_text() function in the AWS SDK for Python (Boto3).

Environment

$ pip install -U boto3
$ pip list | grep boto3
boto3              1.7.82

Sample code

As stated in the document, the text string is 5,000 bytes. Therefore, if it exceeds 5,000 bytes, an error will occur. Since we assume we won’t be translating long sentences for this example, we will cut down the number of bytes using while to avoid errors.

Amazon Translate | TranslateText

The text to translate. The text string can be a maximum of 5,000 bytes long. Depending on your character set, this may be fewer than 5,000 characters.

From English to Japanese

while len(text) > 5000:
  text = text[:-1]

From Japanese to English

while len(text.encode('utf-8')) > 5000:
  text = text[:-1]

Execution

From Japanese to English

text = """自然で正確な言語翻訳"""

Execution result

$ python amazon-translate.py
Natural and accurate language translation

From English to Japanese

text = """Natural and accurate language translation"""

Execution result

$ python amazon-translate.py
自然で正確な言語翻訳

Conclusion

We tried using Amazon Translate to translate from English to Japanese and from Japanese to English. It is easy to use so please try it out.

Reference