babel.messages package¶
Submodules¶
babel.messages.catalog module¶
babel.messages.catalog¶
Data structures for message catalogs.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
babel.messages.catalog.Message(id, string=u'', locations=(), flags=(), auto_comments=(), user_comments=(), previous_id=(), lineno=None, context=None)[source]¶ Bases:
objectRepresentation of a single message in a catalog.
-
check(catalog=None)[source]¶ Run various validation checks on the message. Some validations are only performed if the catalog is provided. This method returns a sequence of TranslationError objects.
Return type: iteratorParameters: catalog – A catalog instance that is passed to the checkers See: Catalog.check for a way to perform checks for all messages in a catalog.
-
fuzzy¶ Whether the translation is fuzzy.
>>> Message('foo').fuzzy False >>> msg = Message('foo', 'foo', flags=['fuzzy']) >>> msg.fuzzy True >>> msg <Message 'foo' (flags: ['fuzzy'])>
Type: bool
-
id= None¶ The message ID
-
pluralizable¶ Whether the message is plurizable.
>>> Message('foo').pluralizable False >>> Message(('foo', 'bar')).pluralizable True
Type: bool
-
python_format¶ Whether the message contains Python-style parameters.
>>> Message('foo %(name)s bar').python_format True >>> Message(('foo %(name)s', 'foo %(name)s')).python_format True
Type: bool
-
string= None¶ The message translation
-
-
class
babel.messages.catalog.Catalog(locale=None, domain=None, header_comment=u'# Translations template for PROJECT.n# Copyright (C) YEAR ORGANIZATIONn# This file is distributed under the same license as the PROJECT project.n# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.n#', project=None, version=None, copyright_holder=None, msgid_bugs_address=None, creation_date=None, revision_date=None, last_translator=None, language_team=None, charset=None, fuzzy=True)[source]¶ Bases:
objectRepresentation of a message catalog.
-
add(id, string=None, locations=(), flags=(), auto_comments=(), user_comments=(), previous_id=(), lineno=None, context=None)[source]¶ Add or update the message with the specified ID.
>>> catalog = Catalog() >>> catalog.add(u'foo') <Message ...> >>> catalog[u'foo'] <Message u'foo' (flags: [])>
This method simply constructs a Message object with the given arguments and invokes __setitem__ with that object.
Parameters: - id – the message ID, or a
(singular, plural)tuple for pluralizable messages - string – the translated message string, or a
(singular, plural)tuple for pluralizable messages - locations – a sequence of
(filenname, lineno)tuples - flags – a set or sequence of flags
- auto_comments – a sequence of automatic comments
- user_comments – a sequence of user comments
- previous_id – the previous message ID, or a
(singular, plural)tuple for pluralizable messages - lineno – the line number on which the msgid line was found in the PO file, if any
- context – the message context
- id – the message ID, or a
-
check()[source]¶ Run various validation checks on the translations in the catalog.
For every message which fails validation, this method yield a
(message, errors)tuple, wheremessageis the Message object anderrorsis a sequence of TranslationError objects.Return type: iterator
-
creation_date= None¶ Creation date of the template
-
delete(id, context=None)[source]¶ Delete the message with the specified ID and context.
Parameters: - id – the message ID
- context – the message context, or
Nonefor no context
-
domain= None¶ The message domain
-
fuzzy= None¶ Catalog header fuzzy bit (True or False)
-
get(id, context=None)[source]¶ Return the message with the specified ID and context.
Parameters: - id – the message ID
- context – the message context, or
Nonefor no context
-
header_comment¶ The header comment for the catalog.
>>> catalog = Catalog(project='Foobar', version='1.0', ... copyright_holder='Foo Company') >>> print catalog.header_comment # Translations template for Foobar. # Copyright (C) ... Foo Company # This file is distributed under the same license as the Foobar project. # FIRST AUTHOR <EMAIL@ADDRESS>, .... #
The header can also be set from a string. Any known upper-case variables will be replaced when the header is retrieved again:
>>> catalog = Catalog(project='Foobar', version='1.0', ... copyright_holder='Foo Company') >>> catalog.header_comment = '''\ ... # The POT for my really cool PROJECT project. ... # Copyright (C) 1990-2003 ORGANIZATION ... # This file is distributed under the same license as the PROJECT ... # project. ... #''' >>> print catalog.header_comment # The POT for my really cool Foobar project. # Copyright (C) 1990-2003 Foo Company # This file is distributed under the same license as the Foobar # project. #
Type: unicode
-
language_team= None¶ Name and email address of the language team.
-
last_translator= None¶ Name and email address of the last translator.
-
locale= None¶ The locale or None
-
mime_headers¶ The MIME headers of the catalog, used for the special
msgid ""entry.The behavior of this property changes slightly depending on whether a locale is set or not, the latter indicating that the catalog is actually a template for actual translations.
Here’s an example of the output for such a catalog template:
>>> from babel.dates import UTC >>> created = datetime(1990, 4, 1, 15, 30, tzinfo=UTC) >>> catalog = Catalog(project='Foobar', version='1.0', ... creation_date=created) >>> for name, value in catalog.mime_headers: ... print '%s: %s' % (name, value) Project-Id-Version: Foobar 1.0 Report-Msgid-Bugs-To: EMAIL@ADDRESS POT-Creation-Date: 1990-04-01 15:30+0000 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME <EMAIL@ADDRESS> Language-Team: LANGUAGE <LL@li.org> MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel ...
And here’s an example of the output when the locale is set:
>>> revised = datetime(1990, 8, 3, 12, 0, tzinfo=UTC) >>> catalog = Catalog(locale='de_DE', project='Foobar', version='1.0', ... creation_date=created, revision_date=revised, ... last_translator='John Doe <jd@example.com>', ... language_team='de_DE <de@example.com>') >>> for name, value in catalog.mime_headers: ... print '%s: %s' % (name, value) Project-Id-Version: Foobar 1.0 Report-Msgid-Bugs-To: EMAIL@ADDRESS POT-Creation-Date: 1990-04-01 15:30+0000 PO-Revision-Date: 1990-08-03 12:00+0000 Last-Translator: John Doe <jd@example.com> Language: de_DE Language-Team: de_DE <de@example.com> Plural-Forms: nplurals=2; plural=(n != 1) MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel ...
Type: list
-
num_plurals¶ The number of plurals used by the catalog or locale.
>>> Catalog(locale='en').num_plurals 2 >>> Catalog(locale='ga').num_plurals 3
Type: int
-
obsolete= None¶ Dictionary of obsolete messages
-
plural_expr¶ The plural expression used by the catalog or locale.
>>> Catalog(locale='en').plural_expr '(n != 1)' >>> Catalog(locale='ga').plural_expr '(n==1 ? 0 : n==2 ? 1 : 2)'
Type: string_types
-
plural_forms¶ Return the plural forms declaration for the locale.
>>> Catalog(locale='en').plural_forms 'nplurals=2; plural=(n != 1)' >>> Catalog(locale='pt_BR').plural_forms 'nplurals=2; plural=(n > 1)'
Type: str
-
project= None¶ The project name
-
revision_date= None¶ Last revision date of the catalog
-
update(template, no_fuzzy_matching=False)[source]¶ Update the catalog based on the given template catalog.
>>> from babel.messages import Catalog >>> template = Catalog() >>> template.add('green', locations=[('main.py', 99)]) <Message ...> >>> template.add('blue', locations=[('main.py', 100)]) <Message ...> >>> template.add(('salad', 'salads'), locations=[('util.py', 42)]) <Message ...> >>> catalog = Catalog(locale='de_DE') >>> catalog.add('blue', u'blau', locations=[('main.py', 98)]) <Message ...> >>> catalog.add('head', u'Kopf', locations=[('util.py', 33)]) <Message ...> >>> catalog.add(('salad', 'salads'), (u'Salat', u'Salate'), ... locations=[('util.py', 38)]) <Message ...>
>>> catalog.update(template) >>> len(catalog) 3
>>> msg1 = catalog['green'] >>> msg1.string >>> msg1.locations [('main.py', 99)]
>>> msg2 = catalog['blue'] >>> msg2.string u'blau' >>> msg2.locations [('main.py', 100)]
>>> msg3 = catalog['salad'] >>> msg3.string (u'Salat', u'Salate') >>> msg3.locations [('util.py', 42)]
Messages that are in the catalog but not in the template are removed from the main collection, but can still be accessed via the obsolete member:
>>> 'head' in catalog False >>> catalog.obsolete.values() [<Message 'head' (flags: [])>]
Parameters: - template – the reference catalog, usually read from a POT file
- no_fuzzy_matching – whether to use fuzzy matching of message IDs
-
version= None¶ The project version
-
babel.messages.checkers module¶
babel.messages.extract module¶
babel.messages.extract¶
Basic infrastructure for extracting localizable messages from source files.
This module defines an extensible system for collecting localizable message strings from a variety of sources. A native extractor for Python source files is builtin, extractors for other sources can be added using very simple plugins.
The main entry points into the extraction functionality are the functions extract_from_dir and extract_from_file.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
babel.messages.extract.extract(method, fileobj, keywords={'pgettext': ((1, 'c'), 2), 'gettext': None, 'ugettext': None, 'N_': None, 'dngettext': (2, 3), 'ungettext': (1, 2), 'dgettext': (2, ), '_': None, 'ngettext': (1, 2)}, comment_tags=(), options=None, strip_comment_tags=False)[source]¶ Extract messages from the given file-like object using the specified extraction method.
This function returns tuples of the form
(lineno, message, comments).The implementation dispatches the actual extraction to plugins, based on the value of the
methodparameter.>>> source = '''# foo module ... def run(argv): ... print _('Hello, world!') ... '''
>>> from StringIO import StringIO >>> for message in extract('python', StringIO(source)): ... print message (3, u'Hello, world!', [], None)
Parameters: - method – a string specifying the extraction method (.e.g. “python”);
if this is a simple name, the extraction function will be
looked up by entry point; if it is an explicit reference
to a function (of the form
package.module:funcnameorpackage.module.funcname), the corresponding function will be imported and used - fileobj – the file-like object the messages should be extracted from
- keywords – a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings
- comment_tags – a list of translator tags to search for and include in the results
- options – a dictionary of additional options (optional)
- strip_comment_tags – a flag that if set to True causes all comment tags to be removed from the collected comments.
Raises ValueError: if the extraction method is not registered
- method – a string specifying the extraction method (.e.g. “python”);
if this is a simple name, the extraction function will be
looked up by entry point; if it is an explicit reference
to a function (of the form
-
babel.messages.extract.extract_from_dir(dirname=None, method_map=[('**.py', 'python')], options_map=None, keywords={'pgettext': ((1, 'c'), 2), 'gettext': None, 'ugettext': None, 'N_': None, 'dngettext': (2, 3), 'ungettext': (1, 2), 'dgettext': (2,), '_': None, 'ngettext': (1, 2)}, comment_tags=(), callback=None, strip_comment_tags=False)[source]¶ Extract messages from any source files found in the given directory.
This function generates tuples of the form
(filename, lineno, message, comments, context).Which extraction method is used per file is determined by the method_map parameter, which maps extended glob patterns to extraction method names. For example, the following is the default mapping:
>>> method_map = [ ... ('**.py', 'python') ... ]
This basically says that files with the filename extension ”.py” at any level inside the directory should be processed by the “python” extraction method. Files that don’t match any of the mapping patterns are ignored. See the documentation of the pathmatch function for details on the pattern syntax.
The following extended mapping would also use the “genshi” extraction method on any file in “templates” subdirectory:
>>> method_map = [ ... ('**/templates/**.*', 'genshi'), ... ('**.py', 'python') ... ]
The dictionary provided by the optional options_map parameter augments these mappings. It uses extended glob patterns as keys, and the values are dictionaries mapping options names to option values (both strings).
The glob patterns of the options_map do not necessarily need to be the same as those used in the method mapping. For example, while all files in the
templatesfolders in an application may be Genshi applications, the options for those files may differ based on extension:>>> options_map = { ... '**/templates/**.txt': { ... 'template_class': 'genshi.template:TextTemplate', ... 'encoding': 'latin-1' ... }, ... '**/templates/**.html': { ... 'include_attrs': '' ... } ... }
Parameters: - dirname – the path to the directory to extract messages from. If not given the current working directory is used.
- method_map – a list of
(pattern, method)tuples that maps of extraction method names to extended glob patterns - options_map – a dictionary of additional options (optional)
- keywords – a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings
- comment_tags – a list of tags of translator comments to search for and include in the results
- callback – a function that is called for every file that message are extracted from, just before the extraction itself is performed; the function is passed the filename, the name of the extraction method and and the options dictionary as positional arguments, in that order
- strip_comment_tags – a flag that if set to True causes all comment tags to be removed from the collected comments.
See: pathmatch
-
babel.messages.extract.extract_from_file(method, filename, keywords={'pgettext': ((1, 'c'), 2), 'gettext': None, 'ugettext': None, 'N_': None, 'dngettext': (2, 3), 'ungettext': (1, 2), 'dgettext': (2, ), '_': None, 'ngettext': (1, 2)}, comment_tags=(), options=None, strip_comment_tags=False)[source]¶ Extract messages from a specific file.
This function returns a list of tuples of the form
(lineno, funcname, message).Parameters: - filename – the path to the file to extract messages from
- method – a string specifying the extraction method (.e.g. “python”)
- keywords – a dictionary mapping keywords (i.e. names of functions that should be recognized as translation functions) to tuples that specify which of their arguments contain localizable strings
- comment_tags – a list of translator tags to search for and include in the results
- strip_comment_tags – a flag that if set to True causes all comment tags to be removed from the collected comments.
- options – a dictionary of additional options (optional)
-
babel.messages.extract.extract_javascript(fileobj, keywords, comment_tags, options)[source]¶ Extract messages from JavaScript source code.
Parameters: - fileobj – the seekable, file-like object the messages should be extracted from
- keywords – a list of keywords (i.e. function names) that should be recognized as translation functions
- comment_tags – a list of translator tags to search for and include in the results
- options – a dictionary of additional options (optional)
-
babel.messages.extract.extract_nothing(fileobj, keywords, comment_tags, options)[source]¶ Pseudo extractor that does not actually extract anything, but simply returns an empty list.
-
babel.messages.extract.extract_python(fileobj, keywords, comment_tags, options)[source]¶ Extract messages from Python source code.
It returns an iterator yielding tuples in the following form
(lineno, funcname, message, comments).Parameters: - fileobj – the seekable, file-like object the messages should be extracted from
- keywords – a list of keywords (i.e. function names) that should be recognized as translation functions
- comment_tags – a list of translator tags to search for and include in the results
- options – a dictionary of additional options (optional)
Return type: iterator
babel.messages.frontend module¶
babel.messages.frontend¶
Frontends for the message extraction functionality.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
babel.messages.frontend.CommandLineInterface[source]¶ Bases:
objectCommand-line interface.
This class provides a simple command-line interface to the message extraction and PO file generation functionality.
-
commands= {'compile': 'compile message catalogs to MO files', 'init': 'create new message catalogs from a POT file', 'extract': 'extract messages from source files and generate a POT file', 'update': 'update existing message catalogs from a POT file'}¶
-
compile(argv)[source]¶ Subcommand for compiling a message catalog to a MO file.
Parameters: argv – the command arguments Since: version 0.9
-
extract(argv)[source]¶ Subcommand for extracting messages from source files and generating a POT file.
Parameters: argv – the command arguments
-
init(argv)[source]¶ Subcommand for creating new message catalogs from a template.
Parameters: argv – the command arguments
-
run(argv=['/home/docs/checkouts/readthedocs.org/user_builds/personfinder/envs/latest/bin/sphinx-build', '-T', '-E', '-b', 'readthedocs', '-d', '_build/doctrees-readthedocs', '-D', 'language=en', '.', '_build/html'])[source]¶ Main entry point of the command-line interface.
Parameters: argv – list of arguments passed on the command-line
-
update(argv)[source]¶ Subcommand for updating existing message catalogs from a template.
Parameters: argv – the command arguments Since: version 0.9
-
usage= '%%prog %s [options] %s'¶
-
version= '%prog 2.1.1'¶
-
-
babel.messages.frontend.check_message_extractors(dist, name, value)[source]¶ Validate the
message_extractorskeyword argument tosetup().Parameters: - dist – the distutils/setuptools
Distributionobject - name – the name of the keyword argument (should always be “message_extractors”)
- value – the value of the keyword argument
Raises DistutilsSetupError: if the value is not valid
- dist – the distutils/setuptools
-
class
babel.messages.frontend.compile_catalog(dist)[source]¶ Bases:
distutils.cmd.CommandCatalog compilation command for use in
setup.pyscripts.If correctly installed, this command is available to Setuptools-using setup scripts automatically. For projects using plain old
distutils, the command needs to be registered explicitly insetup.py:from babel.messages.frontend import compile_catalog setup( ... cmdclass = {'compile_catalog': compile_catalog} )New in version 0.9.
-
boolean_options= ['use-fuzzy', 'statistics']¶
-
description= 'compile message catalogs to binary MO files'¶
-
user_options= [('domain=', 'D', "domain of PO file (default 'messages')"), ('directory=', 'd', 'path to base directory containing the catalogs'), ('input-file=', 'i', 'name of the input file'), ('output-file=', 'o', "name of the output file (default '<output_dir>/<locale>/LC_MESSAGES/<domain>.mo')"), ('locale=', 'l', 'locale of the catalog to compile'), ('use-fuzzy', 'f', 'also include fuzzy translations'), ('statistics', None, 'print statistics about translations')]¶
-
-
class
babel.messages.frontend.extract_messages(dist)[source]¶ Bases:
distutils.cmd.CommandMessage extraction command for use in
setup.pyscripts.If correctly installed, this command is available to Setuptools-using setup scripts automatically. For projects using plain old
distutils, the command needs to be registered explicitly insetup.py:from babel.messages.frontend import extract_messages setup( ... cmdclass = {'extract_messages': extract_messages} )-
boolean_options= ['no-default-keywords', 'no-location', 'omit-header', 'no-wrap', 'sort-output', 'sort-by-file', 'strip-comments']¶
-
description= 'extract localizable strings from the project code'¶
-
user_options= [('charset=', None, 'charset to use in the output file'), ('keywords=', 'k', 'space-separated list of keywords to look for in addition to the defaults'), ('no-default-keywords', None, 'do not include the default keywords'), ('mapping-file=', 'F', 'path to the mapping configuration file'), ('no-location', None, 'do not include location comments with filename and line number'), ('omit-header', None, 'do not include msgid "" entry in header'), ('output-file=', 'o', 'name of the output file'), ('width=', 'w', 'set output line width (default 76)'), ('no-wrap', None, 'do not break long message lines, longer than the output line width, into several lines'), ('sort-output', None, 'generate sorted output (default False)'), ('sort-by-file', None, 'sort output by file location (default False)'), ('msgid-bugs-address=', None, 'set report address for msgid'), ('copyright-holder=', None, 'set copyright holder in output'), ('add-comments=', 'c', 'place comment block with TAG (or those preceding keyword lines) in output file. Separate multiple TAGs with commas(,)'), ('strip-comments', None, 'strip the comment TAGs from the comments.'), ('input-dirs=', None, 'directories that should be scanned for messages. Separate multiple directories with commas(,)')]¶
-
-
class
babel.messages.frontend.init_catalog(dist)[source]¶ Bases:
distutils.cmd.CommandNew catalog initialization command for use in
setup.pyscripts.If correctly installed, this command is available to Setuptools-using setup scripts automatically. For projects using plain old
distutils, the command needs to be registered explicitly insetup.py:from babel.messages.frontend import init_catalog setup( ... cmdclass = {'init_catalog': init_catalog} )-
boolean_options= ['no-wrap']¶
-
description= 'create a new catalog based on a POT file'¶
-
user_options= [('domain=', 'D', "domain of PO file (default 'messages')"), ('input-file=', 'i', 'name of the input file'), ('output-dir=', 'd', 'path to output directory'), ('output-file=', 'o', "name of the output file (default '<output_dir>/<locale>/LC_MESSAGES/<domain>.po')"), ('locale=', 'l', 'locale for the new localized catalog'), ('width=', 'w', 'set output line width (default 76)'), ('no-wrap', None, 'do not break long message lines, longer than the output line width, into several lines')]¶
-
-
babel.messages.frontend.parse_keywords(strings=[])[source]¶ Parse keywords specifications from the given list of strings.
>>> kw = parse_keywords(['_', 'dgettext:2', 'dngettext:2,3', 'pgettext:1c,2']).items() >>> kw.sort() >>> for keyword, indices in kw: ... print (keyword, indices) ('_', None) ('dgettext', (2,)) ('dngettext', (2, 3)) ('pgettext', ((1, 'c'), 2))
-
babel.messages.frontend.parse_mapping(fileobj, filename=None)[source]¶ Parse an extraction method mapping from a file-like object.
>>> buf = BytesIO(b''' ... [extractors] ... custom = mypackage.module:myfunc ... ... # Python source files ... [python: **.py] ... ... # Genshi templates ... [genshi: **/templates/**.html] ... include_attrs = ... [genshi: **/templates/**.txt] ... template_class = genshi.template:TextTemplate ... encoding = latin-1 ... ... # Some custom extractor ... [custom: **/custom/*.*] ... ''')
>>> method_map, options_map = parse_mapping(buf) >>> len(method_map) 4
>>> method_map[0] ('**.py', 'python') >>> options_map['**.py'] {} >>> method_map[1] ('**/templates/**.html', 'genshi') >>> options_map['**/templates/**.html']['include_attrs'] '' >>> method_map[2] ('**/templates/**.txt', 'genshi') >>> options_map['**/templates/**.txt']['template_class'] 'genshi.template:TextTemplate' >>> options_map['**/templates/**.txt']['encoding'] 'latin-1'
>>> method_map[3] ('**/custom/*.*', 'mypackage.module:myfunc') >>> options_map['**/custom/*.*'] {}
Parameters: fileobj – a readable file-like object containing the configuration text to parse See: extract_from_directory
-
class
babel.messages.frontend.update_catalog(dist)[source]¶ Bases:
distutils.cmd.CommandCatalog merging command for use in
setup.pyscripts.If correctly installed, this command is available to Setuptools-using setup scripts automatically. For projects using plain old
distutils, the command needs to be registered explicitly insetup.py:from babel.messages.frontend import update_catalog setup( ... cmdclass = {'update_catalog': update_catalog} )New in version 0.9.
-
boolean_options= ['ignore_obsolete', 'no_fuzzy_matching', 'previous']¶
-
description= 'update message catalogs from a POT file'¶
-
user_options= [('domain=', 'D', "domain of PO file (default 'messages')"), ('input-file=', 'i', 'name of the input file'), ('output-dir=', 'd', 'path to base directory containing the catalogs'), ('output-file=', 'o', "name of the output file (default '<output_dir>/<locale>/LC_MESSAGES/<domain>.po')"), ('locale=', 'l', 'locale of the catalog to compile'), ('width=', 'w', 'set output line width (default 76)'), ('no-wrap', None, 'do not break long message lines, longer than the output line width, into several lines'), ('ignore-obsolete=', None, 'whether to omit obsolete messages from the output'), ('no-fuzzy-matching', 'N', 'do not use fuzzy matching'), ('previous', None, 'keep previous msgids of translated messages')]¶
-
babel.messages.jslexer module¶
babel.messages.jslexer¶
A simple JavaScript 1.5 lexer which is used for the JavaScript extractor.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
class
babel.messages.jslexer.Token[source]¶ Bases:
tupleRepresents a token as returned by tokenize.
-
lineno¶ itemgetter(item, ...) –> itemgetter object
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
-
type¶ itemgetter(item, ...) –> itemgetter object
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
-
value¶ itemgetter(item, ...) –> itemgetter object
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
-
-
babel.messages.jslexer.indicates_division(token)[source]¶ A helper function that helps the tokenizer to decide if the current token may be followed by a division operator.
babel.messages.mofile module¶
babel.messages.mofile¶
Writing of files in the gettext MO (machine object) format.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
babel.messages.mofile.read_mo(fileobj)[source]¶ Read a binary MO file from the given file-like object and return a corresponding Catalog object.
Parameters: fileobj – the file-like object to read the MO file from Note: The implementation of this function is heavily based on the GNUTranslations._parsemethod of thegettextmodule in the standard library.
-
babel.messages.mofile.write_mo(fileobj, catalog, use_fuzzy=False)[source]¶ Write a catalog to the specified file-like object using the GNU MO file format.
>>> from babel.messages import Catalog >>> from gettext import GNUTranslations >>> from StringIO import StringIO
>>> catalog = Catalog(locale='en_US') >>> catalog.add('foo', 'Voh') <Message ...> >>> catalog.add((u'bar', u'baz'), (u'Bahr', u'Batz')) <Message ...> >>> catalog.add('fuz', 'Futz', flags=['fuzzy']) <Message ...> >>> catalog.add('Fizz', '') <Message ...> >>> catalog.add(('Fuzz', 'Fuzzes'), ('', '')) <Message ...> >>> buf = StringIO()
>>> write_mo(buf, catalog) >>> buf.seek(0) >>> translations = GNUTranslations(fp=buf) >>> translations.ugettext('foo') u'Voh' >>> translations.ungettext('bar', 'baz', 1) u'Bahr' >>> translations.ungettext('bar', 'baz', 2) u'Batz' >>> translations.ugettext('fuz') u'fuz' >>> translations.ugettext('Fizz') u'Fizz' >>> translations.ugettext('Fuzz') u'Fuzz' >>> translations.ugettext('Fuzzes') u'Fuzzes'
Parameters: - fileobj – the file-like object to write to
- catalog – the Catalog instance
- use_fuzzy – whether translations marked as “fuzzy” should be included in the output
babel.messages.plurals module¶
babel.messages.plurals¶
Plural form definitions.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
babel.messages.plurals.get_plural(locale='en_US')[source]¶ A tuple with the information catalogs need to perform proper pluralization. The first item of the tuple is the number of plural forms, the second the plural expression.
>>> get_plural(locale='en') (2, '(n != 1)') >>> get_plural(locale='ga') (3, '(n==1 ? 0 : n==2 ? 1 : 2)')
The object returned is a special tuple with additional members:
>>> tup = get_plural("ja") >>> tup.num_plurals 1 >>> tup.plural_expr '0' >>> tup.plural_forms 'npurals=1; plural=0'
Converting the tuple into a string prints the plural forms for a gettext catalog:
>>> str(tup) 'npurals=1; plural=0'
babel.messages.pofile module¶
babel.messages.pofile¶
Reading and writing of files in the gettext PO (portable object)
format.
| copyright: |
|
|---|---|
| license: | BSD, see LICENSE for more details. |
-
babel.messages.pofile.denormalize(string)[source]¶ Reverse the normalization done by the normalize function.
>>> print denormalize(r'''"" ... "Say:\n" ... " \"hello, world!\"\n"''') Say: "hello, world!"
>>> print denormalize(r'''"" ... "Say:\n" ... " \"Lorem ipsum dolor sit " ... "amet, consectetur adipisicing" ... " elit, \"\n"''') Say: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, "
Parameters: string – the string to denormalize
-
babel.messages.pofile.escape(string)[source]¶ Escape the given string so that it can be included in double-quoted strings in
POfiles.>>> escape('''Say: ... "hello, world!" ... ''') '"Say:\\n \\"hello, world!\\"\\n"'
Parameters: string – the string to escape
-
babel.messages.pofile.normalize(string, prefix='', width=76)[source]¶ Convert a string into a format that is appropriate for .po files.
>>> print normalize('''Say: ... "hello, world!" ... ''', width=None) "" "Say:\n" " \"hello, world!\"\n"
>>> print normalize('''Say: ... "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " ... ''', width=32) "" "Say:\n" " \"Lorem ipsum dolor sit " "amet, consectetur adipisicing" " elit, \"\n"
Parameters: - string – the string to normalize
- prefix – a string that should be prepended to every line
- width – the maximum line width; use None, 0, or a negative number to completely disable line wrapping
-
babel.messages.pofile.read_po(fileobj, locale=None, domain=None, ignore_obsolete=False, charset=None)[source]¶ Read messages from a
gettextPO (portable object) file from the given file-like object and return a Catalog.>>> from datetime import datetime >>> from StringIO import StringIO >>> buf = StringIO(''' ... #: main.py:1 ... #, fuzzy, python-format ... msgid "foo %(name)s" ... msgstr "quux %(name)s" ... ... # A user comment ... #. An auto comment ... #: main.py:3 ... msgid "bar" ... msgid_plural "baz" ... msgstr[0] "bar" ... msgstr[1] "baaz" ... ''') >>> catalog = read_po(buf) >>> catalog.revision_date = datetime(2007, 04, 01)
>>> for message in catalog: ... if message.id: ... print (message.id, message.string) ... print ' ', (message.locations, message.flags) ... print ' ', (message.user_comments, message.auto_comments) (u'foo %(name)s', u'quux %(name)s') ([(u'main.py', 1)], set([u'fuzzy', u'python-format'])) ([], []) ((u'bar', u'baz'), (u'bar', u'baaz')) ([(u'main.py', 3)], set([])) ([u'A user comment'], [u'An auto comment'])
New in version 1.0: Added support for explicit charset argument.
Parameters: - fileobj – the file-like object to read the PO file from
- locale – the locale identifier or Locale object, or None if the catalog is not bound to a locale (which basically means it’s a template)
- domain – the message domain
- ignore_obsolete – whether to ignore obsolete messages in the input
- charset – the character set of the catalog.
-
babel.messages.pofile.unescape(string)[source]¶ Reverse escape the given string.
>>> print unescape('"Say:\\n \\"hello, world!\\"\\n"') Say: "hello, world!"
Parameters: string – the string to unescape
-
babel.messages.pofile.write_po(fileobj, catalog, width=76, no_location=False, omit_header=False, sort_output=False, sort_by_file=False, ignore_obsolete=False, include_previous=False)[source]¶ Write a
gettextPO (portable object) template file for a given message catalog to the provided file-like object.>>> catalog = Catalog() >>> catalog.add(u'foo %(name)s', locations=[('main.py', 1)], ... flags=('fuzzy',)) <Message...> >>> catalog.add((u'bar', u'baz'), locations=[('main.py', 3)]) <Message...> >>> from io import BytesIO >>> buf = BytesIO() >>> write_po(buf, catalog, omit_header=True) >>> print buf.getvalue() #: main.py:1 #, fuzzy, python-format msgid "foo %(name)s" msgstr "" #: main.py:3 msgid "bar" msgid_plural "baz" msgstr[0] "" msgstr[1] ""
Parameters: - fileobj – the file-like object to write to
- catalog – the Catalog instance
- width – the maximum line width for the generated output; use None, 0, or a negative number to completely disable line wrapping
- no_location – do not emit a location comment for every message
- omit_header – do not include the
msgid ""entry at the top of the output - sort_output – whether to sort the messages in the output by msgid
- sort_by_file – whether to sort the messages in the output by their locations
- ignore_obsolete – whether to ignore obsolete messages and not include them in the output; by default they are included as comments
- include_previous – include the old msgid as a comment when updating the catalog