Use the gettext module in Python3 to translate Python source code to support multiple languages.

Source: Internet
Author: User

Use the gettext module in Python3 to translate Python source code to support multiple languages.

You have written a Python 3 program and want it to work in other languages. You can copy all the code libraries, and then deliberately check each. py file to replace all the text strings found. But this means that you have two independent copies of your code. Every time you make a change or fix a bug, your workload will be doubled. And if you want programs to work in other languages, it's even worse.

Fortunately, Python provides a solution by using the gettext module.
One Hack Solution

You should change your solution in a unified manner. For example, you can replace each string in your program with a function call (the function name is simpler, for example, like _ (), which returns a string that is translated into the correct language. For example, if your program was originally:
 

print('Hello world!')

...... You can change it:
 

print(_('Hello world!'))

...... Function _ () returns 'Hello world! It is based on the language set by the program. For example, if a global variable named LANGUAGE exists before the LANGUAGE setting, function _ () looks like this:
 

def _(s):  spanishStrings = {'Hello world!': 'Hola Mundo!'}  frenchStrings = {'Hello world!': 'Bonjour le monde!'}  germanStrings = {'Hello world!': 'Hallo Welt!'}   if LANGUAGE == 'English':    return s  if LANGUAGE == 'Spanish':    return spanishStrings[s]  if LANGUAGE == 'French':    return frenchStrings[s]  if LANGUAGE == 'German':    return germanStrings[s]

This is fine, but you are repeating the wheel. The gettext module of Python can do more. Gettext is a series of tools. The file format was invented in 1990s to standardize Software Internationalization (also called I18N ). Gettext is a systematic design for all programming languages, but we will focus only on Python in this article.
Program example

Suppose you have a simple "guess number" game written in Python3 that you want to translate. The source code of the program is here. There are four steps to internationalize the program:

Adjust the source code of the. py file so that the string is input into a function named.
Use the pygettext. py text installed with Python to create a "pot" file from the source code.
Use this free cross-platform Poedit software to create. po and. mo files from the pot file.
Adjust the source code of Your. py file again to import the code of the gettext module and set the language.

Step 1: add the _ () function

First, check all strings in your program that need to be translated and replaced by calls. The gettext system used for Python uses _ () as a common name for the translated string, because it is a short name.

Note: using a format string instead of a connection string will make it easier for your program to translate. For example, your program uses a connection string as follows:
 

print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')print(_('Good job, ') + myName + _('! You guessed my number in ') + guessesTaken + _(' guesses!'))

This results in three separate strings that need to be translated, as opposed to the single string needed in the string formatting approach:
This causes all three independent strings to need to be translated. However, in the format string, only one string needs to be translated:

Print ('Good job, % s! You guessed my number in % s guesses! '% (MyName, guessesTaken ))
Print (_ ('Good job, % s! You guessed my number in % s guesses! ') % (MyName, guessesTaken ))

After you change the source code of "guess number", it will look like this. You cannot run it because the _ () function is not defined yet. This change only allows the pygettext. py text to find all the strings to be translated.
Step 2: Use pygettext. py to extract strings

Tools/i18n In Your Python installation (C: Python34Toolsi18n on Windows) is the pygettext. py text. For common gettext unix Commands of printable strings, the C/C ++ source code is parsed. xgettext unix commands can be used to parse other languages, while pygettext. py knows how to parse the Python source code. It finds all strings and generates a "pot" file.

On Windows, I have run the text like this:
 

C:>py -3.4 C:Python34Toolsi18npygettext.py -d guess guess.py

This creates a pot file named guess. pot. This is just a plain text file, which lists all the strings to be translated for calling the _ () in the source code. You can check the guess. pot file here.
Step 3: Use Poedit to translate strings

You can use a text editor to enter the translation, but the free Poedit software will be easier to download the http://poedit.net from here. Select> New from POT/PO file... Select your guess. po file.

Poedit will ask you what language you want to translate. We use Spanish as an example:

Enter the translation. (I use http://translate.google.com, so it may be a bit strange for people who actually use Spanish .)

The file is saved in its gettext folder. Save to create. po file (a human-readable text file is different from the original. pot file, except for Spanish translation) and. mo file (a machine-readable version that gettext reads. These files are stored in a specific folder so that gettext can find them. They look like this (for example, "es" in Spanish files and "de" in German files "):
 

./guess.py./guess.pot./locale/es/LC_MESSAGES/guess.mo./locale/es/LC_MESSAGES/guess.po./locale/de/LC_MESSAGES/guess.mo./locale/de/LC_MESSAGES/guess.po

These two types of languages are called "es" in Spanish and "de" in German. ISO 639-1 codes is the abbreviation of the language. You don't have to use them, but it makes sense to follow the standards.
Step 4: add the gettext code to your program

Now you have a. mo file that contains translation, and adjust your Python code to use it. Add the following to your program:
 

import gettextes = gettext.translation('guess', localedir='locale', languages=['es'])es.install()

The first 'Guess 'is the "definition field", which actually means the "guess" part of the guess.mo file name. Localedir is the directory address of the locale folder you created. This is a relative or absolute path. Es describes the files in the locale folder. LC_MESSAGES folder is a standard name

The install () method will call _ () to return a string translated as Spanish. If you want to return to the original English language, you only need to assign a lambda function value to _. This will return the input string:
 

import gettextes = gettext.translation('guess', localedir='locale', languages=['es'])print(_('Hello! What is your name?')) # prints Spanish _ = lambda s: s

You can check the source code of "Guess the Number" to be translated. If you want to run this program, download and unzip the compressed file, its locale folder, and The. mo Installation File.
Additional reading

I cannot call it I18N or gettext experts. If my tutorial is not well explained, please leave a message. In most cases, when your software runs, it does not convert the LANGUAGE. Instead, it reads LANGUAGE, LC_ALL, LC_MESSAGES, and LANG environment variables to determine the location of the computer. I will update this tutorial while learning.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.