Translation classes are what actually implement the translation of original source file message strings to translated message strings. The base class used by all translation classes is
NullTranslations
; this provides the basic interface you can use to write your own specialized translation classes. Here are the methods of
NullTranslations
:
The
gettext
module provides one additional class derived from
NullTranslations
:
GNUTranslations
. This class overrides
_parse()
to enable reading GNU
gettext
format
.mo
files in both big-endian and little-endian format.
GNUTranslations
parses optional metadata out of the translation catalog. It is convention with GNU
gettext
to include metadata as the translation for the empty string. This metadata is in
RFC 822
-style
key: value
pairs, and should contain the
Project-Id-Version
key. If the key
Content-Type
is found, then the
charset
property is used to initialize the “protected”
_charset
instance variable, defaulting to
None
if not found. If the charset encoding is specified, then all message ids and message strings read from the catalog are converted to Unicode using this encoding, else ASCII is assumed.
Since message ids are read as Unicode strings too, all
*gettext()
methods will assume message ids as Unicode strings, not byte strings.
The entire set of key/value pairs are placed into a dictionary and set as the “protected”
_info
实例变量。
若
.mo
file’s magic number is invalid, the major version number is unexpected, or if other problems occur while reading the file, instantiating a
GNUTranslations
class can raise
OSError
.
-
class
gettext.
GNUTranslations
¶
-
The following methods are overridden from the base class implementation:
-
gettext
(
message
)
¶
-
Look up the
message
id in the catalog and return the corresponding message string, as a Unicode string. If there is no entry in the catalog for the
message
id, and a fallback has been set, the look up is forwarded to the fallback’s
gettext()
method. Otherwise, the
message
id is returned.
-
ngettext
(
singular
,
plural
,
n
)
¶
-
Do a plural-forms lookup of a message id.
singular
is used as the message id for purposes of lookup in the catalog, while
n
is used to determine which plural form to use. The returned message string is a Unicode string.
If the message id is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback’s
ngettext()
method. Otherwise, when
n
is 1
singular
is returned, and
plural
is returned in all other cases.
这里是范例:
n = len(os.listdir('.'))
cat = GNUTranslations(somefile)
message = cat.ngettext(
'There is %(num)d file in this directory',
'There are %(num)d files in this directory',
n) % {'num': n}
-
pgettext
(
context
,
message
)
¶
-
Look up the
context
and
message
id in the catalog and return the corresponding message string, as a Unicode string. If there is no entry in the catalog for the
message
id and
context
, and a fallback has been set, the look up is forwarded to the fallback’s
pgettext()
method. Otherwise, the
message
id is returned.
Added in version 3.8.
-
npgettext
(
context
,
singular
,
plural
,
n
)
¶
-
Do a plural-forms lookup of a message id.
singular
is used as the message id for purposes of lookup in the catalog, while
n
is used to determine which plural form to use.
If the message id for
context
is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback’s
npgettext()
method. Otherwise, when
n
is 1
singular
is returned, and
plural
is returned in all other cases.
Added in version 3.8.
Solaris message catalog support
¶
The Solaris operating system defines its own binary
.mo
file format, but since no documentation can be found on this format, it is not supported at this time.
分类构造函数
¶
GNOME uses a version of the
gettext
module by James Henstridge, but this version has a slightly different API. Its documented usage was:
import gettext
cat = gettext.Catalog(domain, localedir)
_ = cat.gettext
print(_('hello world'))
For compatibility with this older module, the function
Catalog()
is an alias for the
translation()
function described above.
One difference between this module and Henstridge’s: his catalog objects supported access through a mapping API, but this appears to be unused and so is not currently supported.
国际化您的程序和模块
¶
Internationalization (I18N) refers to the operation by which a program is made aware of multiple languages. Localization (L10N) refers to the adaptation of your program, once internationalized, to the local language and cultural habits. In order to provide multilingual messages for your Python programs, you need to take the following steps:
-
prepare your program or module by specially marking translatable strings
-
run a suite of tools over your marked files to generate raw messages catalogs
-
create language-specific translations of the message catalogs
-
使用
gettext
module so that message strings are properly translated
In order to prepare your code for I18N, you need to look at all the strings in your files. Any string that needs to be translated should be marked by wrapping it in
_('...')
— that is, a call to the function
_
。例如:
filename = 'mylog.txt'
message = _('writing a log message')
with open(filename, 'w') as fp:
fp.write(message)
In this example, the string
'writing a log message'
is marked as a candidate for translation, while the strings
'mylog.txt'
and
'w'
are not.
There are a few tools to extract the strings meant for translation. The original GNU
gettext
only supported C or C++ source code but its extended version
xgettext
scans code written in a number of languages, including Python, to find strings marked as translatable.
Babel
is a Python internationalization library that includes a
pybabel
script to extract and compile message catalogs. François Pinard’s program called
xpot
does a similar job and is available as part of his
po-utils package
.
(Python also includes pure-Python versions of these programs, called
pygettext.py
and
msgfmt.py
; some Python distributions will install them for you.
pygettext.py
类似于
xgettext
, but only understands Python source code and cannot handle other programming languages such as C or C++.
pygettext.py
supports a command-line interface similar to
xgettext
; for details on its use, run
pygettext.py
--help
.
msgfmt.py
is binary compatible with GNU
msgfmt
. With these two programs, you may not need the GNU
gettext
package to internationalize your Python applications.)
xgettext
,
pygettext
, and similar tools generate
.po
files that are message catalogs. They are structured human-readable files that contain every marked string in the source code, along with a placeholder for the translated versions of these strings.
Copies of these
.po
files are then handed over to the individual human translators who write translations for every supported natural language. They send back the completed language-specific versions as a
<language-name>.po
file that’s compiled into a machine-readable
.mo
binary catalog file using the
msgfmt
program. The
.mo
files are used by the
gettext
module for the actual translation processing at run-time.
How you use the
gettext
module in your code depends on whether you are internationalizing a single module or your entire application. The next two sections will discuss each case.
本地化您的模块
¶
If you are localizing your module, you must take care not to make global changes, e.g. to the built-in namespace. You should not use the GNU
gettext
API but instead the class-based API.
Let’s say your module is called “spam” and the module’s various natural language translation
.mo
files reside in
/usr/share/locale
in GNU
gettext
format. Here’s what you would put at the top of your module:
import gettext
t = gettext.translation('spam', '/usr/share/locale')
_ = t.gettext
本地化您的应用程序
¶
If you are localizing your application, you can install the
_()
function globally into the built-in namespace, usually in the main driver file of your application. This will let all your application-specific files just use
_('...')
without having to explicitly install it in each file.
In the simple case then, you need only add the following bit of code to the main driver file of your application:
import gettext
gettext.install('myapplication')
If you need to set the locale directory, you can pass it into the
install()
函数:
import gettext
gettext.install('myapplication', '/usr/share/locale')
Changing languages on the fly
¶
If your program needs to support many languages at the same time, you may want to create multiple translation instances and then switch between them explicitly, like so:
import gettext
lang1 = gettext.translation('myapplication', languages=['en'])
lang2 = gettext.translation('myapplication', languages=['fr'])
lang3 = gettext.translation('myapplication', languages=['de'])
# start by using language1
lang1.install()
# ... time goes by, user selects language 2
lang2.install()
# ... more time goes by, user selects language 3
lang3.install()
延迟翻译
¶
In most coding situations, strings are translated where they are coded. Occasionally however, you need to mark strings for translation, but defer actual translation until later. A classic example is:
animals = ['mollusk',
'albatross',
'rat',
'penguin',
'python', ]
# ...
for a in animals:
print(a)
Here, you want to mark the strings in the
animals
list as being translatable, but you don’t actually want to translate them until they are printed.
Here is one way you can handle this situation:
def _(message): return message
animals = [_('mollusk'),
_('albatross'),
_('rat'),
_('penguin'),
_('python'), ]
del _
# ...
for a in animals:
print(_(a))
This works because the dummy definition of
_()
simply returns the string unchanged. And this dummy definition will temporarily override any definition of
_()
in the built-in namespace (until the
del
command). Take care, though if you have a previous definition of
_()
in the local namespace.
Note that the second use of
_()
will not identify “a” as being translatable to the
gettext
program, because the parameter is not a string literal.
Another way to handle this is with the following example:
def N_(message): return message
animals = [N_('mollusk'),
N_('albatross'),
N_('rat'),
N_('penguin'),
N_('python'), ]
# ...
for a in animals:
print(_(a))
In this case, you are marking translatable strings with the function
N_()
, which won’t conflict with any definition of
_()
. However, you will need to teach your message extraction program to look for translatable strings marked with
N_()
.
xgettext
,
pygettext
,
pybabel extract
,和
xpot
all support this through the use of the
-k
command-line switch. The choice of
N_()
here is totally arbitrary; it could have just as easily been
MarkThisStringForTranslation()
.