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

Source: Internet
Author: User
Tags gettext i18n locale readable

You write a Python 3 program and want it to work in other languages. You can copy all the code base and then deliberately check each. py file to replace all the found text strings. But that means you have two separate copies of your code, and every time you make a change or fix a bug, your workload doubles. And if you want the program to apply to other languages, it's even worse.

Luckily, Python has a solution, which is to use 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 (simple, 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 _ () returns ' Hello world! ' Translation, which is based on the language that the program sets. For example, if the language setting is preceded by 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]

That's OK, but you're making wheels over and over again. Python's gettext modules can do more. GetText is a series of tools, the file format was 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 by Python3 that you want to translate. The source code of the program is here. There are four steps to internationalize this program:

Adjust the source code for this. py file so that the string is entered into a function named _ ().
Create a "pot" file from the source code with the pygettext.py text that is 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 of the GetText module and set the language.

First step: Add _ () function

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

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

Print (' Good job, ' + MyName + '! You guessed I number in ' + Guessestaken + ' guesses! ')
Print (' Good job, ') + MyName + _ ('! You guessed me number in ') + Guessestaken + _ (' guesses! ')

This is results in three separate strings which need to is 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 format string, just translate a string:

Print (' Good job,%s! You guessed I number in%s guesses! '% (myname, Guessestaken))
Print (' Good job,%s! You guessed me number in%s guesses! ') % (MyName, Guessestaken))

When you finish the "Guess number" source code, it will be like this. You can't run it because the _ () function is not defined yet. This change just lets pygettext.py text 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 strings Common GetText UNIX commands to parse C + + source and xgettext UNIX commands can parse other languages, and pygettext.py knows how to parse the python source. 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 a plain text file, it lists all the source in the search for _ () the call to translate the string. You can read the Guess.pot file here.
Step Three: Use Poedit to translate strings

You can use a text editor to fill out translations 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 folder. Saving creates a. po file (a human-readable text file differs from the original. pot file, except for Spanish translations) and a. Mo file (a machine-readable version of the machine that a gettext will read.) These files will exist in a specific folder so that GetText can find them. They look like this (e.g. "Es" in the Spanish file and "de" in the German file):

./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, like "es" in Spanish and "de" in German, are called ISO 639-1 codes are standard abbreviations for languages. You don't have to use them, but it makes sense to follow the rules.
Step Fourth: Add gettext code to your program

Now you have the. Mo file containing the translation, and adjust your Python code to use it. Add the following in your program:

Import GetText
es = gettext.translation (' Guess ', localedir= ' locale ', languages=[' es ')
es.install ()

The first ' guess ' is the "definition field", which 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 file below the locale folder. The Lc_messages folder is a standard name

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

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

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

I am not a i18n or gettext expert, if my tutorials are not good enough, please be sure to leave a message. Most of the time, your software does not convert the language, but instead reads Language,lc_all,lc_messages, and Lang, one of these environment variables to determine where the computer works. I will update this tutorial while I am learning.

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.