How do i translate in python?

❮ String Methods


Example

Replace any "S" characters with a "P" character:

#use a dictionary with ascii codes to replace 83 (S) with 80 (P):
mydict = {83:  80}
txt = "Hello Sam!"
print(txt.translate(mydict))

Try it Yourself »


Definition and Usage

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.

If you use a dictionary, you must use ascii codes instead of characters.


Syntax

Parameter Values

ParameterDescription
table Required. Either a dictionary, or a mapping table describing how to perform the replace

More Examples

Example

Use a mapping table to replace "S" with "P":

txt = "Hello Sam!"
mytable = txt.maketrans("S", "P")
print(txt.translate(mytable))

Try it Yourself »

Example

Use a mapping table to replace many characters:

txt = "Hi Sam!"
x = "mSa"
y = "eJo"
mytable = txt.maketrans(x, y)
print(txt.translate(mytable))

Try it Yourself »

Example

The third parameter in the mapping table describes characters that you want to remove from the string:

txt = "Good night Sam!"
x = "mSa"
y = "eJo"
z = "odnght"
mytable = txt.maketrans(x, y, z)
print(txt.translate(mytable))

Try it Yourself »

Example

The same example as above, but using a dictionary instead of a mapping table:

txt = "Good night Sam!"
mydict = {109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104: None, 116: None}
print(txt.translate(mydict))

Try it Yourself »


❮ String Methods


The string translate() method returns a string where each character is mapped to its corresponding character in the translation table.

translate() method takes the translation table to replace/translate characters in the given string as per the mapping table.

The translation table is created by the static method maketrans().

The syntax of the translate() method is:

string.translate(table)

String translate() Parameters

translate() method takes a single parameter:

  • table - a translation table containing the mapping between two characters; usually created by maketrans()

Return value from String translate()

translate() method returns a string where each character is mapped to its corresponding character as per the translation table.


Example 1: Translation/Mapping using a translation table with translate()

# first string
firstString = "abc"
secondString = "ghi"
thirdString = "ab"

string = "abcdef"
print("Original string:", string)

translation = string.maketrans(firstString, secondString, thirdString)

# translate string
print("Translated string:", string.translate(translation))

Output

Original string: abcdef
Translated string: idef

Here, the translation mapping translation contains the mapping from a, b and c to g, h and i respectively.

But, the removal string thirdString resets the mapping to a and b to None.

So, when the string is translated using translate(), a and b are removed, and c is replaced i outputting idef.

Note: If you cannot understand what's going inside maketrans(), please refer to String maketrans().


Example 2: Translation/Mapping with translate() with manual translation table

# translation table - a dictionary
translation = {97: None, 98: None, 99: 105}

string = "abcdef"
print("Original string:", string)

# translate string
print("Translated string:", string.translate(translation))

Output

Original string: abcdef
Translated string: idef

Here, we don't create a translation table from maketrans() but, we manually create the mapping dictionary translation.

This translation is then used to translate string to get the same output as the previous example.

  · 6 min read · Updated sep 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 makes unofficial Ajax calls to Google Translate API to detect languages and translate text.

This library is not just for translation, we have a tutorial on how to detect languages using this exact library among others.

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 it 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 calls 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 the 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 great for everyone who 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 will 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 and documents on the command line. Check it out 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 much 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 in python?


Comment panel

Can we translate language in python?

Practical Data Science using Python The python package which helps us do this is called translate. This package can be installed by the following way. It provides translation for major languages. Below is an example of translating a simple sentence from English to German.

Which translator is used in python?

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

How do I import a translation into python?

Installation. pip install translate. Or, you can download the source and python setup.py install. ... .
Command-Line Usage. In your command-line: translate "This is a pen." ... .
Use As A Python Module. from translate import Translator translator= Translator(to_lang="zh") translation = translator. translate("This is a pen.").

How do I translate Arabic to English in python?

“python code to translate english to arabic” Code Answer.
# First install translate with pip in cmd..
pip install translate..
# Code..
from translate import Translator..
translator= Translator(from_lang="german",to_lang="spanish").
translation = translator. translate("Guten Morgen").
print(translation).