How do you translate text using Python?

Introduction

At some point, you must have tried Google Translate to translate some text from one language to the other. But, do you know how Google does that? Well, Google developers have created an API that does it all.

To translate the text from one language to another using Python, we are going to use a package named googletrans that has been called internally to the Google Translate API. However, we do not need to worry about the internal calling of the API; instead, we can go ahead and directly use the package.

First, let’s install the package by running the following command:

pip install googletrans==3.1.0a0

Now, let’s look at the code:

from googletrans import Translator
translator = Translator()
translated_text = translator.translate('안녕하세요.')
print(translated_text.text)
translated_text = translator.translate('안녕하세요.', dest='ja')
print(translated_text.text)
translated_text = translator.translate('veritas lux mea', src='la')
print(translated_text.text)
  • On line 1, we imported the required package.
  • On line 3, we created an instance of Translator class and assigned it to translator variable.
  • On line 5, we performed the translation of the text. (If the source language is not given, google translate attempts to detect the source language. If the target language is not given, it will translate your text to English by default.)
  • On line 6, we printed the translated text.
  • On line 8, we translated the text in Korean to Japanese by specifying the destination, or target language, as ja.
  • On line 9, we printed the translated text.
  • On line 11, we translated the text in Latin by specifying the source language. We did not specify the target language, so the text will be translated to English by default.
  • On line 12, we printed the translated text.

So, in this way, you can easily use Google Translate to translate your text using Python.