Python 3.8+gettextfunction
gettext.npgettext()
contextual translation
A contextual, plural-aware translation using the current global domain.
Syntax
text = gettext.npgettext(context, singular, plural, n, /)
The catalog key combines the context with the English forms: 'context\x04singular\x00plural'. The form is chosen by the catalog's Plural-Forms rule; without a catalog it is the English n == 1. As with ngettext, insert the number into the string yourself.
Examples
import io, struct
def mo(cat): # собрать каталог .mo в памяти
cat = {'': 'Content-Type: text/plain; charset=UTF-8\n', **cat}
ks = sorted(cat)
bs = [k.encode() for k in ks] + [cat[k].encode() for k in ks]
n, data, tab = len(ks), b'', b''
for b in bs:
tab += struct.pack('<2I', len(b), 28 + 16 * n + len(data))
data += b + b'\0'
return struct.pack('<7I', 0x950412de, 0, n, 28, 28 + 8 * n, 0, 0) + tab + data
H = 'Content-Type: text/plain; charset=UTF-8\nPlural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n'
import gettext
import os
os.makedirs('loc/ru/LC_MESSAGES', exist_ok=True)
open('loc/ru/LC_MESSAGES/app.mo', 'wb').write(mo({'': H, 'inbox\x04message\x00messages': 'письмо\x00письма\x00писем'}))
os.environ['LANGUAGE'] = 'ru'
gettext.bindtextdomain('app', 'loc')
gettext.textdomain('app')
print([gettext.npgettext('inbox', 'message', 'messages', n) for n in (1, 3, 7)]) # → ['письмо', 'письма', 'писем']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy