i18n
— i18n Support#
Various i18n functions.
Helper functions for both the internal localization system and for TranslateWiki-based translations.
By default messages are assumed to reside in a package called ‘scripts.i18n’. In pywikibot 3+, that package is not packaged with pywikibot, and pywikibot 3+ does not have a hard dependency on any i18n messages. However, there are three user input questions in pagegenerators which will use i18n messages if they can be loaded.
The default message location may be changed by calling
set_message_package
with a package name. The package must contain an
__init__.py, and a message bundle called ‘pywikibot’ containing messages.
See twtranslate
for more information on the messages.
Imports in pywikibot
module
The following function is inported in pywikibot
module but can also
be used as pywikibot
members:
- i18n.bundles(stem=False)[source]#
A generator which yields message bundle names or its path objects.
The bundle name usually corresponds with the script name which is localized.
With
stem=True
the bundle names are given:>>> from pywikibot import i18n >>> bundles = sorted(i18n.bundles(stem=True)) >>> len(bundles) 39 >>> bundles[:4] ['add_text', 'archivebot', 'basic', 'blockpageschecker'] >>> bundles[-5:] ['unlink', 'unprotect', 'unusedfiles', 'weblinkchecker', 'welcome'] >>> 'pywikibot' in bundles True
With
stem=False
we get Path objects:>>> path = next(i18n.bundles()) >>> path.is_dir() True >>> path.parent.as_posix() 'scripts/i18n'
Added in version 7.0.
- Parameters:
stem (bool) – yield the Path.stem if True and the Path object otherwise
- Return type:
Generator[Path | str, None, None]
- i18n.get_bot_prefix(source, use_prefix)[source]#
Get the bot prefix string like ‘Bot: ‘ including space delimiter.
Note
If source is a str and
config.bot_prefix
is set to None, it cannot be determined whether the current user is a bot account. In this cas the prefix will be returned.Added in version 8.1.
- Parameters:
source (str | BaseSite) – When it’s a site it’s using the lang attribute and otherwise it is using the value directly.
use_prefix (bool) – If True, return a bot prefix which depends on the
config.bot_prefix
setting.
- Return type:
str
- i18n.input(twtitle, parameters=None, password=False, fallback_prompt=None)[source]#
Ask the user a question, return the user’s answer.
The prompt message is retrieved via
twtranslate
and uses the config variable ‘userinterface_lang’.- Parameters:
twtitle (str) – The TranslateWiki string title, in <package>-<key> format
parameters (Mapping[str, int] | None) – The values which will be applied to the translated text
password (bool) – Hides the user’s input (for password entry)
fallback_prompt (str | None) – The English prompt if i18n is not available.
- Return type:
str
- i18n.known_languages()[source]#
All languages we have localizations for.
>>> from pywikibot import i18n >>> i18n.known_languages()[:10] ['ab', 'aeb', 'af', 'am', 'an', 'ang', 'anp', 'ar', 'arc', 'ary'] >>> i18n.known_languages()[-10:] ['vo', 'vro', 'wa', 'war', 'xal', 'xmf', 'yi', 'yo', 'yue', 'zh'] >>> len(i18n.known_languages()) 255
The implementation is roughly equivalent to:
langs = set() for dirpath in bundles(): for fname in dirpath.iterdir(): if fname.suffix == '.json': langs.add(fname.stem) return sorted(langs)
Added in version 7.0.
- Return type:
list[str]
- i18n.messages_available()[source]#
Return False if there are no i18n messages available.
To determine if messages are available, it looks for the package name set using
set_messages_package
for a message bundle calledpywikibot
containing messages.>>> from pywikibot import i18n >>> i18n.messages_available() True >>> old_package = i18n._messages_package_name # save the old package name >>> i18n.set_messages_package('foo') >>> i18n.messages_available() False >>> i18n.set_messages_package(old_package) >>> i18n.messages_available() True
- Return type:
bool
- i18n.set_messages_package(package_name)[source]#
Set the package name where i18n messages are located.
- Parameters:
package_name (str)
- Return type:
None
- i18n.translate(code, xdict, parameters=None, fallback=False)[source]#
Return the most appropriate localization from a localization dict.
Given a site code and a dictionary, returns the dictionary’s value for key ‘code’ if this key exists; otherwise tries to return a value for an alternative code that is most applicable to use on the wiki in language ‘code’ except fallback is False.
The code itself is always checked first, then these codes that have been defined to be alternatives, and finally English.
If fallback is False and the code is not found in the
For PLURAL support have a look at the twtranslate method.
- Parameters:
code (str | BaseSite) – The site code as string or Site object. If xdict is an extended dictionary the Site object should be used in favour of the code string. Otherwise localizations from a wrong family might be used.
xdict (str | Mapping[str, str]) – dictionary with language codes as keys or extended dictionary with family names as keys containing code dictionaries or a single string. May contain PLURAL tags as described in twtranslate
parameters (Mapping[str, int] | None) – For passing (plural) parameters
fallback (bool | Iterable[str]) – Try an alternate language code. If it’s iterable it’ll also try those entries and choose the first match.
- Returns:
the localized string
- Raises:
IndexError – If the language supports and requires more plurals than defined for the given PLURAL pattern.
KeyError – No fallback key found if fallback is not False
- Return type:
str | None
- i18n.twget_keys(twtitle)[source]#
Return all language codes for a special message.
- Parameters:
twtitle (str) – The TranslateWiki string title, in <package>-<key> format
- Raises:
OSError – the package i18n cannot be loaded
- Return type:
list[str]
- i18n.twhas_key(source, twtitle)[source]#
Check if a message has a translation in the specified language code.
The translations are retrieved from i18n.<package>, based on the callers import table.
No code fallback is made.
- Parameters:
source (str | BaseSite) – When it’s a site it’s using the lang attribute and otherwise it is using the value directly.
twtitle (str) – The TranslateWiki string title, in <package>-<key> format
- Return type:
bool
- i18n.twtranslate(source, twtitle, parameters=None, *, fallback=True, fallback_prompt=None, only_plural=False, bot_prefix=False)[source]#
Translate a message using JSON files in messages_package_name.
fallback parameter must be True for i18n and False for L10N or testing purposes.
Support for plural is implemented like in MediaWiki extension. If the TranslateWiki message contains a plural tag inside which looks like:
{{PLURAL:<number>|<variant1>|<variant2>[|<variantn>]}}
it takes that variant calculated by the plural_rules depending on the number value. Multiple plurals are allowed.
As an examples, if we had several json dictionaries in test folder like:
en.json:
{ "test-plural": "Bot: Changing %(num)s {{PLURAL:%(num)d|page|pages}}.", }
fr.json:
{ "test-plural": \ "Robot: Changer %(descr)s {{PLURAL:num|une page|quelques pages}}.", }
and so on.
>>> # this code snippet is running in test environment >>> # ignore test message "tests: max_retries reduced from 15 to 1" >>> import os >>> os.environ['PYWIKIBOT_TEST_QUIET'] = '1'
>>> from pywikibot import i18n >>> i18n.set_messages_package('tests.i18n') >>> # use a dictionary >>> str(i18n.twtranslate('en', 'test-plural', {'num':2})) 'Bot: Changing 2 pages.' >>> # use additional format strings >>> str(i18n.twtranslate( ... 'fr', 'test-plural', {'num': 1, 'descr': 'seulement'})) 'Robot: Changer seulement une page.' >>> # use format strings also outside >>> str(i18n.twtranslate( ... 'fr', 'test-plural', {'num': 10}, only_plural=True ... ) % {'descr': 'seulement'}) 'Robot: Changer seulement quelques pages.'
Changed in version 8.1: the bot_prefix parameter was added.
- Parameters:
source (str | BaseSite) – When it’s a site it’s using the lang attribute and otherwise it is using the value directly. The site object is recommended.
twtitle (str) – The TranslateWiki string title, in <package>-<key> format
parameters (Sequence[str] | Mapping[str, int] | None) – For passing parameters. It should be a mapping but for backwards compatibility can also be a list, tuple or a single value. They are also used for plural entries in which case they must be a Mapping and will cause a TypeError otherwise.
fallback (bool) – Try an alternate language code
fallback_prompt (str | None) – The English message if i18n is not available
only_plural (bool) – Define whether the parameters should be only applied to plural instances. If this is False it will apply the parameters also to the resulting string. If this is True the placeholders must be manually applied afterwards.
bot_prefix (bool) – If True, prepend the message with a bot prefix which depends on the
config.bot_prefix
setting
- Raises:
IndexError – If the language supports and requires more plurals than defined for the given translation template.
- Return type:
str | None