all Python 3gettextterm
gettext.GNUTranslations
translation catalogs
A translation catalog that reads a binary GNU gettext .mo file. It understands plural forms and message context.
Syntax
t = gettext.GNUTranslations(fp)
It reads a compiled .mo, not a text .po: build the .po first with msgfmt (or Tools/i18n/msgfmt.py). The plural rule comes from the catalog's Plural-Forms header, so the three Russian forms work only when that header is present; without it the English n != 1 applies. The constructor takes an open binary file, not a path.
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'
cat = {'': H, 'Hello': 'Привет', 'file\0files': 'файл\0файла\0файлов'}
import gettext
t = gettext.GNUTranslations(io.BytesIO(mo(cat)))
print(t.gettext('Hello')) # → Привет
print([t.ngettext('file', 'files', n) for n in (1, 3, 5, 21)]) # → ['файл', 'файла', 'файлов', 'файл']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy