Chapter XV: internationalization and localization -gettext: Message catalogs - a complex value

15.1.4 complex-valued
simple conversion can handle most message needs replacement, but the complex gettext treated as a special case. There will be between singular and plural forms of a different message, but also on the specific language, the difference may be different, but somewhat different at the end of a word, while others are oranges whole structure is different. According to the complex level, it may also have different forms. To make it easier to manage a plurality of (in certain cases even be able to manage complex), the module provides a set of separate functions to interrogate the plural form of a message.

from gettext import translation
import sys

t = translation('plural','locale',fallback=False)
num = int(sys.argv[1])
msg = t.ngettext('{num} means singular.',
                 '{num} means plural.',
                 num)

# Still need to add the values to the message ourselves
print(msg.format(num=num))

Use ungettext () to access the plural versions of a message. Parameter is to be converted messages and the number of items.

Here Insert Picture Description
Because some form of conversion candidates, these alternate forms are listed in an array. By using an array, the conversion can be completed for a variety of complex forms of language (e.g., Polish on different forms to indicate the relative quantity).
Here Insert Picture Description
In addition to converting the string to fill, but also need to tell the library which uses the plural form, it knows the value corresponding to a given number of how index in the array. OK "Plural-Forms: nplurals = INTEGER ; plural = EXPRESSION; \ n" contains two values, need to manually replace: nplurals is an integer indicating the size of the array (the number of conversion used); plural is a C language expression, the resulting number is used to index into an array required to locate a conversion. N literal strings are passed to the replaced ungettext () number.
For example, it includes two English plural form. The number 0 will be treated as plural ( "0 bananas"). Plural-Forms following items.

Plural-Forms: nplurals = 2; plural = n = 1;!
Singular conversion at position 0, position a plurality of conversion.
Here Insert Picture Description

After compiling the catalog, run a few tests script, showing how different values ​​of N is converted to an index for string conversion.

Guess you like

Origin blog.csdn.net/weixin_43193719/article/details/94760475