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

Source: Internet
Author: User
Tags i18n locale
You wrote 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, replacing all the found text strings. But that means you have two separate copies of your code, and your workload doubles whenever you make a change or fix a bug. And if you want the program to work in other languages, it's even worse.

Fortunately, Python has given a solution by using the GetText module.
A hack solution

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

Print (' Hello world! ')

...... You can change it to:

Print (_ (' Hello world! '))

...... function _ () will return ' Hello world! ' Translation, which is based on the language set by the program. For example, if the language is set up before a global variable called language, the function _ () looks like this:

def _ (s):  spanishstrings = {' Hello world! ': ' Hola mundo! '}  Frenchstrings = {' Hello world! ': ' Bonjour le monde! '}  Germanstrings = {' Hello world! ': ' Hallo welt! '}   if LANGUAGE = = ' 中文版 ':    return s  if LANGUAGE = = ' Spanish ':    return spanishstrings[s]  if LANGUAGE = = ' Fre Nch ':    return frenchstrings[s]  if LANGUAGE = = ' German ':    return germanstrings[s]

This is possible, but you're making the wheel again. Python's GetText module can do more. GetText is a series of tools that were invented in the 1990s to standardize software internationalization (also known as i18n). GetText is a systematic design for all programming languages, but we will focus only on Python in this article.
Program examples

Imagine 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 make this program internationalized:

Adjust the source code for this. py file so that the string is entered into a function called _ ().
Create a "pot" file from the source code with the pygettext.py text installed with Python.
Use this free cross-platform Poedit software to create. PO and. Mo files from pot files.
Adjust your. py File source code again to import the code for the GetText module, setting the language.

First step: Add _ () function

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

Note: Using a format string instead of a concatenated string will be easier for your program to translate. For example, with a concatenated string your program would look like this:

Print (' Good job, ' + MyName + '! 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 being translated, as opposed to the single string needed in the string fo Rmatting approach:
This causes three separate strings to be translated, but instead in a formatted string, simply translate a string:

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

When you have changed the "Guess number" source code, it will look like this. You cannot run it because the _ () function is not yet defined. This change simply allows the pygettext.py text to find all the strings that need to be translated.
Step Two: Extract the string with pygettext.py

The tools/i18n in your Python installation (c:python34toolsi18n on Windows) is the pygettext.py text. For translatable string Ordinary gettext Unix command parsing c/C + + source and xgettext Unix command can parse other languages, and pygettext.py know how to parse Python source code. It will find all the strings and produce a "pot" file.

On Windows I've run this text like this:

c:>py-3.4 c:python34toolsi18npygettext.py-d Guess guess.py

This creates a pot file called Guess.pot. This is just plain text file, it lists all the calls in the source code to find _ () to translate the string. You can see the Guess.pot file here.
Step three: Translating strings with Poedit

You can fill in the translation with a text editor but free Poedit software will be easier to download from here http://poedit.net. Select > New from Pot/po file ... Then select your Guess.po file.

Poedit will ask you what language you want to translate into. For example, we use the Spanish language:

Fill in the translation. (I use http://translate.google.com, so it's kind of weird for people who really use Spanish.) )

Now save the file in its GetText form in the folder. Save creates a. po file (a human-readable text file differs from the original. pot file, except for Spanish translations) and an. Mo file (a machine-readable version that GetText reads. These files will exist 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 properties of language like "es" in Spanish and "de" in German are called ISO 639-1 codes is the standard abbreviation for language. You don't have to use them, but it makes sense to follow the standards.
Fourth Step: Add gettext code to your program

Now that you have the. Mo file containing the translation, tweak 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 ' define domain ', which actually means the "guess" part of the Guess.mo file name. Localedir is the directory address of the locale folder you created. This will be a relative or absolute path. ' es ' describes the files under the locale folder. Lc_messages folder is a standard name

The install () method causes the call _ () to return a string translated into Spanish. If you want to return to the original English only need to assign a lambda function value to _, this will return the string entered at that time:

Import gettextes = gettext.translation (' Guess ', localedir= ' locale ', languages=[' es ') print (_ (' hello! What is your name? ')) # prints Spanish _ = Lambda s:s

You can check the "Guess the number" source for translation. If you want to run this program, download and unzip the compressed file and its locale folder and the. Mo installation file.
Extended Reading

I do not call the i18n or GetText experts, if my tutorial is not good enough, please be sure to leave a message. In most cases, your software runs without translating the language, but instead reads Language,lc_all,lc_messages, and one of these environment variables to determine where the computer works. I will be learning while updating this tutorial.

  • Related Article

    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.