PyI18N翻译:YAML语言文件结构配置故障排查求助
问题根源
- YAML文件结构错误:你的
en.yml多了一层外层的en:键,PyI18N的加载器期望直接读取翻译内容,不需要额外嵌套语言代码键。 - 初始化方式与API不匹配:PyI18N构造函数的第一个参数应为可用语言元组,之前的报错并非元组参数本身的问题,而是YAML结构错误导致加载失败。
修正方案
1. 调整YAML文件结构
修改en.yml,移除外层的en:键,直接保留翻译节点:
labels: products: Products messages: welcome: Welcome
同理修改pl.yml示例:
labels: products: Produkty messages: welcome: Witaj
2. 修正初始化代码
恢复传入可用语言元组,同时简化gettext调用(无需重复传入locale参数):
from pyi18n import PyI18n import sys if __name__ == "__main__": available_locales: tuple[str] = ('en', 'pl') user_locale: str = input('Enter your locale: ').lower() if user_locale not in available_locales: print('Locale not supported, please select another one') sys.exit(1) # 传入所有可用语言,指定默认语言为用户选择的locale i18n: PyI18n = PyI18n(available_locales, default_locale=user_locale) _ = i18n.gettext # 直接传入翻译键即可 print(_('messages.welcome')) print("============================") print(_('labels.products')) # 如需临时切换语言,可添加locale参数: # print(_('messages.welcome', locale='pl'))
3. 确认目录结构
保持原目录结构不变:
. ├── locales │ ├── en.yml │ └── pl.yml └── store.py
测试结果
运行脚本后输入en,输出:
Enter your locale: en Welcome ============================ Products
输入pl则输出对应波兰语翻译。
原错误解释
- 传入元组时报错:YAML多了外层
en:键,加载器尝试读取ser_mod.load(...)['en'],但实际加载后的结构是{'en': {...}},与加载器期望的直接翻译字典不匹配,导致返回None触发TypeError。 - 传入单个locale后提示翻译缺失:加载后的翻译结构为
{'en': {'labels': ..., 'messages': ...}},gettext直接查找messages.welcome时无法匹配嵌套路径,因此提示缺失。
内容的提问来源于stack exchange,提问作者Sidharth Samant
相关产品推荐
相关产品推荐

