我一直在尝试按照此处所示的步骤进行操作。老实说,它们并不是 100% 完美,我不得不到处调整一些东西,但这就是我的最终脚本。
from pyi18n import PyI18n
import sys
if __name__ == "__main__":
available_locales: tuple[str] = ('en', 'pl')
user_locale: str = input('Enter your locale: ')
if user_locale.lower() not in available_locales:
print('Locale not supported, please select another one')
sys.exit(1)
i18n: PyI18n = PyI18n(user_locale)
_ = i18n.gettext
print(_(user_locale, 'messages.welcome'))
print("============================")
print(_(user_locale, 'labels.products'))
请注意,我将单个字符串作为参数传递给
PyI18n
,因为传递了文档中所示的字符串元组,给了我这个错误。
Traceback (most recent call last):
File "/Users/sidharthsamant/Documents/scripts/localisation-poc/store.py", line 13, in <module>
i18n: PyI18n = PyI18n(available_locales)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/pyi18n/pyi18n.py", line 62, in __init__
self.__pyi18n_init()
File "/opt/homebrew/lib/python3.11/site-packages/pyi18n/pyi18n.py", line 80, in __pyi18n_init
self._loaded_translations: dict = self.loader.load(
^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/pyi18n/loaders.py", line 200, in load
return super().load(locales, yaml)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/pyi18n/loaders.py", line 75, in load
loaded[locale] = self.__load_file(file_path,
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/pyi18n/loaders.py", line 100, in __load_file
return ser_mod.load(_f, **load_params)[locale]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
TypeError: 'NoneType' object is not subscriptable
将字符串元组更改为单个字符串后,这是我的目录结构
.
├── locales
│ ├── en.yml
│ └── pl.yml
└── store.py
但是当我运行
store.py
传递 en
作为语言时,我得到了这个
Enter your locale: en
missing translation for: en.messages.welcome
============================
missing translation for: en.labels.products
这是我的
en.yml
en:
labels:
products: Products
messages:
welcome: Welcome
YAML结构/语法似乎是错误的,但我在网上找不到任何相关文档。甚至 Github 存储库 (link) 中的示例 YAML 也具有相同的格式。
有人可以帮忙吗?
我偶然发现这个话题,你处理这个问题了吗?我是这个库的作者。
PyI18n
类应使用 available_locales
参数创建,而不是用户的输入(当前区域设置)。这就是您收到此错误的原因,因为 PyI18n
init 函数需要可用区域设置的元组,因此您的代码应该是:
available_locales: tuple[str] = ('en', 'pl')
i18n: PyI18n = PyI18n(available_locales)
_ = i18n.gettext