Code for How to Translate Languages in Python Tutorial

View on Github

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

# 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))

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 =
    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)
            filename, ext = basename.split(".")
            # 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)
        # not a file, just text, print the translated text to standard output
        print(translate(target, src=src, dest=dest))


python --help


usage: [-h] [-s SOURCE] [-d DESTINATION] target

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

    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
    -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 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 'Bonjour' -s fr -d en