Detect and Translate in Python
In this tutorial, we are going to learn how to translate text in Python. Firstly, make sure that your computer is connected to the internet. And also, you need to install a module called googletrans to work this program. You can download the module by entering the following command in your command prompt. Let’s get some idea about googletrans module.
pip install googletrans
Googletrans module
Googletrans is a Python module developed by Google, it is developed using Google Translate API. So, this module can detect and translate the text. googletrans supports many languages. To know the languages supported by googletrans use the following code.
import googletrans print(googletrans.LANGUAGES)
Output:-
{'af': 'afrikaans', 'sq': 'albanian', 'am': 'amharic', 'ar': 'arabic', 'hy': 'armenian', 'az': 'azerbaijani', 'eu': 'basque', 'be': 'belarusian', 'bn': 'bengali', 'bs': 'bosnian', 'bg': 'bulgarian', 'ca': 'catalan', 'ceb': 'cebuano', ...............}
As a result, this code prints all the languages supported by googletrans module.
Detecting Text
To detect the language of the given text we use detect function from the translator class present in the module. Let’s see an example.
from googletrans import Translator translator = Translator() t = "नमस्ते दुनिया" ex = translator.detect(t) print(ex)
In the above example, we have entered the text into the ‘t’ variable and sent it as a parameter to the detect function. And we are storing the output of the detect method in the ‘ex’ variable and printing it.
Output:-
Detected(lang=hi, confidence=1.0)
The output says that the language is Hindi and the confidence level of the model.
Translating Text
To translate the text we use the translate method present in the translator class. Translate class takes three parameters as the input they are text (which we want to translate), src (language of the given text) and dest (the language in which we want to translate). Let’s see an example.
from googletrans import Translator translator = Translator() trans = translator.translate(text='Hello World', src='en', dest='hi') trans2 = translator.translate(text='Hello', src='en', dest='es') print(trans.text) print(trans2.text)
Output:-
नमस्ते दुनिया Hola
As a result, we get the translated text as output. The first text is translated into Hindi and the second text is translated into Spanish.
Also, read: Python program to remove all the special characters from a text file
Leave a Reply