Ashish Bansal
Ashish Bansal

Reputation: 111

I need to translate the English .txt file to German language using AWS translate service and boto3

I am able to convert particular English words to German words. But I am looking to convert the entire local.txt file.

import boto3

translate = boto3.client(service_name='translate', region_name='us-east-1', use_ssl=True)

result = translate.translate_text(Text="Good Evening", 
        SourceLanguageCode="en", TargetLanguageCode="de")
print('TranslatedText: ' + result.get('TranslatedText'))
print('SourceLanguageCode: ' + result.get('SourceLanguageCode'))
print('TargetLanguageCode: ' + result.get('TargetLanguageCode'))

I am looking for a way to convert the streaming data or local text file and then save it to S3 or locally.

Upvotes: 2

Views: 370

Answers (1)

bigbiffnotbigbiff
bigbiffnotbigbiff

Reputation: 73

Since I don't have an AWS account, I can't test the API directly. However, I can offer what I believe would work.

First, read the text file you want to translate into a variable.

with open('text_to_translate.txt', 'r') as text:
   variable_containing_text = text.read()

Then, simply feed the translator the variable, rather than a string.

result = translate.translate_text(Text=variable_containing_text, 
        SourceLanguageCode="en", TargetLanguageCode="de")

When placed into your code, it should look like this:

import boto3

data = 'file.txt'

translate = boto3.client(service_name='translate', region_name='us-east-1', use_ssl=True)

with open(file, 'r') as text:
   data = text.read()

result = translate.translate_text(Text=data, 
        SourceLanguageCode="en", TargetLanguageCode="de")
print('TranslatedText: ' + result.get('TranslatedText'))
print('SourceLanguageCode: ' + result.get('SourceLanguageCode'))
print('TargetLanguageCode: ' + result.get('TargetLanguageCode'))

Upvotes: 1

Related Questions