How do i translate a python to english?

  · 6 min read · Updated jul 2022 · Application Programming Interfaces · Natural Language Processing

Disclosure: This post may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.

Google translate is a free service that translates words, phrases and entire web pages into more than 100 languages. You probably already know it and you have used it many times in your life.

In this tutorial, you will learn how to perform language translation in Python using Googletrans library. Googletrans is a free and unlimited Python library that make unofficial Ajax calls to Google Translate API in order to detect languages and translate text.

Here are the main features of this library:

  • Auto language detection (it offers language detection as well)
  • Bulk translations
  • Fast & reliable
  • HTTP/2 support
  • Connection pooling

Note that Googletrans makes API calls to the Google translate API, if you want a reliable use, then consider using an official API or making your own machine translation machine learning model.

First, let's install it using pip:

pip3 install googletrans

Translating Text

Importing necessary libraries:

from googletrans import Translator, constants
from pprint import pprint

Googletrans provides us with a convenient interface, let's initialize our translator instance:

# init the Google API translator
translator = Translator()

Note that Translator class has several optional arguments:

  • service_urls: This should be a list of strings that are the URLs of google translate API, an example is ["translate.google.com", "translate.google.co.uk"].
  • user_agent: A string that will be included in User-Agent header in the request.
  • proxies (dictionary): A Python dictionary that maps protocol or protocol and host to the URL of the proxy, an example is {'http': 'example.com:3128', 'http://domain.example': 'example.com:3555'}, more on proxies in this tutorial.
  • timeout: The timeout of each request you make, expressed in seconds.

Now we simply use translate() method to get the translated text:

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

This will print the original text and language along with the translated text and language:

Hola Mundo (es) --> Hello World (en)

If the above code results in an error like this:

AttributeError: 'NoneType' object has no attribute 'group'

Then you have to uninstall the current googletrans version and install the new one using the following commands:

$ pip3 uninstall googletrans
$ pip3 install googletrans==3.1.0a0

Going back to the code, it automatically detects the language and translate to english by default, let's translate to another language, arabic for instance:

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

"ar" is the language code for arabic, here is the output:

Hola Mundo (es) --> مرحبا بالعالم (ar)

Now let's set a source language and translate to English:

# specify source language
translation = translator.translate("Wie gehts ?", src="de")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")

Output:

Wie gehts ? (de) --> How are you ? (en)

You can also check other translations and some other extra data:

# print all translations and other data
pprint(translation.extra_data)

See the output:

{'all-translations': [['interjection',
                       ['How are you doing?', "What's up?"],
                       [['How are you doing?', ["Wie geht's?"]],
                        ["What's up?", ["Wie geht's?"]]],
                       "Wie geht's?",
                       9]],
 'confidence': 1.0,
 'definitions': None,
 'examples': None,
 'language': [['de'], None, [1.0], ['de']],
 'original-language': 'de',
 'possible-mistakes': None,
 'possible-translations': [['Wie gehts ?',
                            None,
                            [['How are you ?', 1000, True, False],
                             ["How's it going ?", 1000, True, False],
                             ['How are you?', 0, True, False]],
                            [[0, 11]],
                            'Wie gehts ?',
                            0,
                            0]],
 'see-also': None,
 'synonyms': None,
 'translation': [['How are you ?', 'Wie gehts ?', None, None, 1]]}

A lot of data to benefit from, you have all the possible translations, confidence, definitions and even examples.

Translating List of Phrases

You can also pass a list of text to translate each sentence individually:

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

Output:

Hello everyone (en) --> herkese merhaba (tr)
How are you ? (en) --> Nasılsın ? (tr)
Do you speak english ? (en) --> İngilizce biliyor musunuz ? (tr)
Good bye! (en) --> Güle güle! (tr)

Language Detection

Google Translate API offers us language detection call as well:

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

This will print the code of the detected language along with confidence rate (1.0 means 100% confident):

Language code: hi
Confidence: 1.0

This will return the language code, to get the full language name, you can use the LANGUAGES dictionary provided by Googletrans:

print("Language:", constants.LANGUAGES[detection.lang])

Output:

Language: hindi

Supported Languages

As you may know, Google Translate supports more than 100 languages, let's print all of them:

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

Here is a truncated output:

Total supported languages: 107
{'af': 'afrikaans',
 'sq': 'albanian',
 'am': 'amharic',
 'ar': 'arabic',
 'hy': 'armenian',
...

...
 'vi': 'vietnamese',
 'cy': 'welsh',
 'xh': 'xhosa',
 'yi': 'yiddish',
 'yo': 'yoruba',
 'zu': 'zulu'}

Conclusion

There you have it, this library is a great deal for everyone that wants a quick way to translate text in an application. However, this library is unofficial as mentioned earlier, the author noted that the maximum character length on a single text is 15K.

It also doesn't guarantee that the library would work properly at all times, if you want to use a stable API you should use the official Google Translate API.

If you get HTTP 5xx errors with this library, then Google has banned your IP address, it's because using this library a lot, Google translate may block your IP address, you'll need to consider using proxies by passing a proxy dictionary to proxies parameter in Translator() class, or use the official API as discussed.

Also, I've written a quick Python script that will allow you to translate text into sentences as well as in documents in the command line, check it here.

Finally, I encourage you to further explore the library, check out its official documentation.

Finally, if you're a beginner and want to learn Python, I suggest you take the Python For Everybody Coursera course, in which you'll learn a lot about Python. You can also check our resources and courses page to see the Python resources I recommend!

Learn also: How to Convert Text to Speech in Python.

Happy Coding ♥

View Full Code


Read Also


How do i translate a python to english?

How do i translate a python to english?


Comment panel

How do I translate python to English?

How do you translate text using Python?.
from googletrans import Translator..
translator = Translator().
translated_text = translator. translate('안녕하세요. ').
print(translated_text. text).
translated_text = translator. translate('안녕하세요.', dest='ja').

How do you translate a file in python?

Translating Text Documents You can also translate text documents via Google Translate API. All you have to do is to read the text file in Python using the open method, read the text and pass it to the translate() method. You can also check whether or not the file is in "read" mode using the mode property: if f.

Is there a translate function in python?

The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table. Use the maketrans() method to create a mapping table. If a character is not specified in the dictionary/table, the character will not be replaced.

What type of translator is used for python?

Python googletrans is a module to translate text. It uses the Google Translate Ajax API to detect langauges and translate text.