51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
"""国际化模块:提供 t(key, **kwargs) 翻译函数,支持语言切换。
|
|
|
|
模块导入时自动加载 zh_CN 作为默认语言。
|
|
通过 switch(locale) 切换语言,t() 返回当前语言的翻译文本。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
_I18N_DIR = Path(__file__).parent
|
|
_translations: dict[str, str] = {}
|
|
_current_locale: str = "zh_CN"
|
|
|
|
|
|
def load(locale: str) -> None:
|
|
"""加载指定语言的翻译文件。"""
|
|
global _translations, _current_locale
|
|
_current_locale = locale
|
|
path = _I18N_DIR / f"{locale}.json"
|
|
if path.exists():
|
|
_translations = json.loads(path.read_text(encoding="utf-8"))
|
|
else:
|
|
_translations = {}
|
|
|
|
|
|
def switch(locale: str) -> None:
|
|
"""切换当前语言并返回新语言代码。"""
|
|
load(locale)
|
|
|
|
|
|
def current_locale() -> str:
|
|
"""返回当前语言代码。"""
|
|
return _current_locale
|
|
|
|
|
|
def t(key: str, **kwargs: object) -> str:
|
|
"""获取翻译文本,支持 {name} 插值。
|
|
|
|
如果 key 不存在,返回 key 本身作为回退。
|
|
"""
|
|
text = str(_translations.get(key, key))
|
|
if kwargs:
|
|
text = text.format(**{k: v for k, v in kwargs.items()})
|
|
return text
|
|
|
|
|
|
# 模块导入时自动加载默认中文翻译
|
|
load("zh_CN")
|