We can use a language translator to translate text from one language to another.
There are various APIs and modules for this, we’ll use the Google Translate API.
Scripting is where Python really pays off. The Python Scripting Essentials Bundle has the kind of small automation projects you would build for work.
Python can translate text for you with an API. The goslate module is a
small wrapper around the Google Translate API, and it does detection and batch
translation as well.
We will use the Goslate module to translate. Apart from translation, it supports
language detection, batch translation, dictionary lookup and more.
Installation
The goslate module connects with the Google Translate API.
The first step is to install the goslate module.
Install goslate using pyenv, pipenv or virtualenv.
Example
With just a few lines of code we can translate English to French.
|
Change the second parameter in gs.translate to alter the language.
Other Translate APIs
There are a few other translation APIS including:
- Google Cloud Platform
- mstranslate - Microsoft(Bing) translate API for python3
- gp-python-client - IBM Bluemix
- yandex-translater - API for Yandex Translate
- No known module - Baidu Translation API
Do you know of any other modules? leave a comment.
Alternatives
If there is no module available for the translation API,
you could make your own module using beautifulsoup.
Offline Translation
This is a simple dictionary translation (offline). If you want a simple word translation, you can use this.Use your package manager to install dictd,
sudo pacman -S dictd
sudo apt-get install dictd
Then to list databases
dict -D
To translate a single word:
dict -d fd-eng-spa "earth"
We create this code to list all translations:
import os
word = 'earth'
translation = os.popen('dict -d fd-eng-spa ' + word).read()
print(translation)
The steps
from goslate import Goslateandg = Goslate().g.translate('hello', 'nl')returns the Dutch for hello.g.detect('hallo wereld')gives you back the language code it thinks it is.g.languagesis a list of every language code, so you can build a picker from it.g.translate(text, 'en', 'nl')says what it is and what you want.- Pass a list of sentences to translate a whole batch in one call.
A free Google Translate account has a limit per day. Past that you need an API key,
which you pass to Goslate with Goslate('your-key').
For a small fixed set of languages you can also skip the API and use a dictionary or a language file you ship yourself. That avoids the network call and the limit.
The fastest way to learn this is to write it yourself. The PyChallenge exercises run in your browser, no install needed.
