locale-plus 🌍
Документация на русском
Simplified internationalization (i18n) in Python. Locale format conversion between Windows and Unix systems, convenient loading of .mo translation files.
Features
- 🔄 Locale conversion between Windows (e.g.,
Russian_Russia) and Unix formats (ru_RU) - 🌐 Determine the current system locale with automatic conversion
- 📖 Load GNU gettext translations from
.mofiles - 💾 Cache translations for optimal performance
- 🔧 Support for singular and plural forms (plural forms)
Installation
pip install locale-plus
Or for development:
git clone https://github.com/yourusername/locale-plus.git
cd locale-plus
pip install -e .
Requirements
- Python 3.8 or higher
bidict >= 0.23.1pathlike-typing >= 1.0.0
Quick Start
Locale Conversion
from locale_plus import LocaleConverter
# Get the current system locale
current = LocaleConverter.current_language
print(current) # 'ru_RU' or 'en_US' etc.
# Convert Windows -> Unix
unix_locale = LocaleConverter.convert_windows_to_unix('Russian_Russia')
print(unix_locale) # 'ru_RU'
# Convert Unix -> Windows
windows_locale = LocaleConverter.convert_unix_to_windows('ru_RU')
print(windows_locale) # 'Russian_Russia'
Using Translations
Directory structure for translation files:
locales/
├── ru_RU/
│ └── LC_MESSAGES/
│ └── messages.mo
├── en_US/
│ └── LC_MESSAGES/
│ └── messages.mo
└── de_DE/
└── LC_MESSAGES/
└── messages.mo
from locale_plus import Internationalizator
# Create an object for the Russian locale
i18n = Internationalizator(
locale_dir='locales',
language_code='ru_RU',
domain='messages'
)
# Simple Translation
print(i18n.gettext('Hello World!')) # 'Hello World!'
# Translation with Plural Forms
for i in range(5):
print(i18n.ngettext(f'{i} file', f'{i} files', i))
Working with Locale Dictionaries
from locale_plus import LocaleConverter
# Get all Windows -> Unix mappings
win_to_unix = LocaleConverter.windows_unix_locales
print(win_to_unix['Russian_Russia']) # 'ru_RU'
# Get all Unix -> Windows mappings
unix_to_win = LocaleConverter.unix_windows_locales
print(unix_to_win['ru_RU']) # 'Russian_Russia'
API Reference
LocaleConverter (static class)
| Property/Method | Description |
|---|---|
| windows_unix_locales | Dictionary mapping Windows → Unix formats |
| unix_windows_locales | Dictionary mapping Unix → Windows formats |
| convert_windows_to_unix(locale) | Converts a Windows locale to Unix format |
| convert_unix_to_windows(locale) | Converts a Unix locale to Windows format |
| current_language | Returns the current system locale in Unix format |
Internationalizator
Internationalizator(locale_dir, language_code, domain)
| Parameter | Type | Description |
|---|---|---|
| locale_dir | PathLike | Path to the directory with locale files |
| language_code | str | Language code (e.g., 'ru_RU') |
| domain | str | Translation domain (the .mo file name) |
Methods:
gettext(message)- translates a stringngettext(singular, plural, n)- translates with plural forms supportpgettext(context)- translation with context supportnpgettext(context)- translation with context and plural form support
Supported Locales
The module supports conversion for 35 popular locales:
| Language | Windows | Unix |
|---|---|---|
| Russian | Russian_Russia | ru_RU |
| English (USA) | English_United States | en_US |
| English (UK) | English_United Kingdom | en_GB |
| German | German_Germany | de_DE |
| French | French_France | fr_FR |
| Spanish | Spanish_Spain | es_ES |
| Chinese | Chinese_China | zh_CN |
| Japanese | Japanese_Japan | ja_JP |
| ...and others | ... | ... |
Development
Installation for Development
git clone https://github.com/yourusername/locale_plus.git
cd locale_plus
pip install -e ".[dev]"
Building the Package
python -m build
License
MIT License. See the LICENSE file for details.
Author
Mag Ilyas DOMA (MagIlyasDOMA) - @MagIlyasDOMA
Acknowledgements
bidictlibrary for efficient bidirectional dictionaries- GNU gettext for the translation file standard
⭐ Please star if the project was useful!
locale-plus 🌍
Documentation in English
Упрощённая работа с интернационализацией (i18n) в Python. Конвертация форматов локалей между Windows и Unix системами, удобная загрузка .mo файлов переводов.
Возможности
- 🔄 Конвертация локалей между Windows (например,
Russian_Russia) и Unix форматами (ru_RU) - 🌐 Определение текущей локали системы с автоматической конвертацией
- 📖 Загрузка GNU gettext переводов из
.moфайлов - 💾 Кэширование переводов для оптимальной производительности
- 🔧 Поддержка единственного и множественного числа (plural forms)
Установка
pip install locale-plus
Или для разработки:
git clone https://github.com/yourusername/locale-plus.git
cd locale-plus
pip install -e .
Требования
- Python 3.8 или выше
bidict >= 0.23.1pathlike-typing >= 1.0.0
Быстрый старт
Конвертация локалей
from locale_plus import LocaleConverter
# Определение текущей локали системы
current = LocaleConverter.current_language
print(current) # 'ru_RU' или 'en_US' и т.д.
# Конвертация Windows -> Unix
unix_locale = LocaleConverter.convert_windows_to_unix('Russian_Russia')
print(unix_locale) # 'ru_RU'
# Конвертация Unix -> Windows
windows_locale = LocaleConverter.convert_unix_to_windows('ru_RU')
print(windows_locale) # 'Russian_Russia'
Использование переводов
Структура директорий для файлов переводов:
locales/
├── ru_RU/
│ └── LC_MESSAGES/
│ └── messages.mo
├── en_US/
│ └── LC_MESSAGES/
│ └── messages.mo
└── de_DE/
└── LC_MESSAGES/
└── messages.mo
from locale_plus import Internationalizator
# Создаём объект для русской локали
i18n = Internationalizator(
locale_dir='locales',
language_code='ru_RU',
domain='messages'
)
# Простой перевод
print(i18n.gettext('Hello World!')) # 'Привет Мир!'
# Перевод с учётом множественного числа
for i in range(5):
print(i18n.ngettext(f'{i} file', f'{i} files', i))
Работа со словарями локалей
from locale_plus import LocaleConverter
# Получить все соответствия Windows -> Unix
win_to_unix = LocaleConverter.windows_unix_locales
print(win_to_unix['Russian_Russia']) # 'ru_RU'
# Получить все соответствия Unix -> Windows
unix_to_win = LocaleConverter.unix_windows_locales
print(unix_to_win['ru_RU']) # 'Russian_Russia'
API Справка
LocaleConverter (статический класс)
| Свойство/Метод | Описание |
|---|---|
| windows_unix_locales | Словарь соответствия Windows → Unix форматов |
| unix_windows_locales | Словарь соответствия Unix → Windows форматов |
| convert_windows_to_unix(locale) | Конвертирует Windows локаль в Unix формат |
| convert_unix_to_windows(locale) | Конвертирует Unix локаль в Windows формат |
| current_language | Возвращает текущую системную локаль в Unix формате |
Internationalizator
Internationalizator(locale_dir, language_code, domain)
| Параметр | Тип | Описание |
|---|---|---|
| locale_dir | PathLike | Путь к директории с файлами локалей |
| language_code | str | Код языка (например, 'ru_RU') |
| domain | str | Имя домена перевода (имя .mo файла) |
Методы:
gettext(message)- перевод строкиngettext(singular, plural, n)- перевод с поддержкой plural formspgettext(context)- перевод с поддержкой контекстаnpgettext(context)- перевод с поддержкой контекста и plural forms
Поддерживаемые локали
Модуль поддерживает конвертацию для 35 популярных локалей:
| Язык | Windows | Unix |
|---|---|---|
| Русский | Russian_Russia | ru_RU |
| Английский (США) | English_United States | en_US |
| Английский (Великобритания) | English_United Kingdom | en_GB |
| Немецкий | German_Germany | de_DE |
| Французский | French_France | fr_FR |
| Испанский | Spanish_Spain | es_ES |
| Китайский | Chinese_China | zh_CN |
| Японский | Japanese_Japan | ja_JP |
| ...и другие | ... | ... |
Разработка
Установка для разработки
git clone https://github.com/yourusername/locale_plus.git
cd locale_plus
pip install -e ".[dev]"
Сборка пакета
python -m build
Лицензия
MIT License. См. файл LICENSE для деталей.
Автор
Маг Ильяс DOMA (MagIlyasDOMA) - @MagIlyasDOMA
Благодарности
- Библиотека
bidictдля эффективных двунаправленных словарей - GNU gettext для стандарта файлов переводов
⭐ Поставьте звезду, если проект оказался полезным!
Metadata
Release files for locale-plus 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| locale_plus-0.2.0.tar.gz | 7.1 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| locale_plus-0.2.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 14.4 kB
Release files / locale_plus-0.2.0.tar.gz
| Download URL | locale_plus-0.2.0.tar.gz |
|---|---|
| Size | 7.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a3e938203f8d8e96dc2ba8000131c6ae2b9d58ec94265b859cdffab9bb386825
|
|
BLAKE2b-256 checksum How to use checksums |
6db5e9cb61984fa30e595e60c27ed61505c43f0776d803bf555d8e36eb331753
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.5
|
Release files / locale_plus-0.2.0-py3-none-any.whl
| Download URL | locale_plus-0.2.0-py3-none-any.whl |
|---|---|
| Size | 7.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e97dc1f854a8088790058e0b89e748eb9fc5990a7ced872b48ce9ac4edf56952
|
|
BLAKE2b-256 checksum How to use checksums |
ab58079bb4987a32aecba013849076b22f3572a038dab2974dad31a1b32df203
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.5
|