Code for How to Translate Languages in Python Tutorial


View on Github

translator.py

from googletrans import Translator, constants
from pprint import pprint

# init the Google API translator
translator = Translator()

# translate a spanish text to english text (by default)
translation = translator.translate("Hola Mundo")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")

# translate a spanish text to arabic for instance
translation = translator.translate("Hola Mundo", dest="ar")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")

# specify source language
translation = translator.translate("Wie gehts ?", src="de")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")
# print all translations and other data
pprint(translation.extra_data)

# translate more than a phrase
sentences = [
    "Hello everyone",
    "How are you ?",
    "Do you speak english ?",
    "Good bye!"
]
translations = translator.translate(sentences, dest="tr")
for translation in translations:
    print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")

# detect a language
detection = translator.detect("नमस्ते दुनिया")
print("Language code:", detection.lang)
print("Confidence:", detection.confidence)
# print the detected language
print("Language:", constants.LANGUAGES[detection.lang])

# print all available languages
print("Total supported languages:", len(constants.LANGUAGES))
print("Languages:")
pprint(constants.LANGUAGES)

translate_doc.py

from googletrans import Translator
import argparse
import os

# init the translator
translator = Translator()

def translate(text, src="auto", dest="en"):
    """Translate `text` from `src` language to `dest`"""
    return translator.translate(text, src=src, dest=dest).text
    

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Simple Python script to translate text using Google Translate API (googletrans wrapper)")
    parser.add_argument("target", help="Text/Document to translate")
    parser.add_argument("-s", "--source", help="Source language, default is Google Translate's auto detection", default="auto")
    parser.add_argument("-d", "--destination", help="Destination language, default is English", default="en")
    
    args = parser.parse_args()
    target = args.target
    src = args.source
    dest = args.destination
    
    if os.path.isfile(target):
        # translate a document instead
        # get basename of file
        basename = os.path.basename(target)
        # get the path dir
        dirname = os.path.dirname(target)
        try:
            filename, ext = basename.split(".")
        except:
            # no extension
            filename = basename
            ext = ""

        translated_text = translate(open(target).read(), src=src, dest=dest)
        # write to new document file
        open(os.path.join(dirname, f"{filename}_{dest}{f'.{ext}' if ext else ''}"), "w").write(translated_text)
    else:
        # not a file, just text, print the translated text to standard output
        print(translate(target, src=src, dest=dest))

Usage:

python translate_doc.py --help

Output:

usage: translate_doc.py [-h] [-s SOURCE] [-d DESTINATION] target

    Simple Python script to translate text using Google Translate API (googletrans
    wrapper)

    positional arguments:
    target                Text/Document to translate

    optional arguments:
    -h, --help            show this help message and exit
    -s SOURCE, --source SOURCE
                            Source language, default is Google Translate's auto
                            detection
    -d DESTINATION, --destination DESTINATION
                            Destination language, default is English

For instance, if you want to translate text in the document wonderland.txt from English (en) to Arabic (ar), you can use:

python translate_doc.py wonderland.txt --source en --destination ar

A new file wonderland_ar.txt will appear in the current directory that contains the translated document.

You can also translate text and print in the stdout:

python translate_doc.py 'Bonjour' -s fr -d en

Output:

'Hello'


🕒 Black Friday Limited-Time Offer!
EBook Image

Black Friday Week Special! Get our eBook Bundle at 52% off. Limited time only!

$102.0 $49.0