如果您只有几种语言,并且不想使用一些 i18n 的东西,请尝试以下其中一种:
示例(我只是在 py 文件中使用 dict,如果您想要专门的 json,请告诉我):
另外,这是用 python 3 而不是 2 编写的。
在en.py
en = {
"eng": "english",
"heb": "hebrew",
"menu": {
"menu1": "one",
"menu2": "two"
}
}
在he.py
he = {
"eng": "אנגלית",
"heb": "עברית",
"menu": {
"menu1": "אחד",
"menu2": "שתיים"
}
}
使用 SimpleNamespace 的选项 1:
from types import SimpleNamespace
#import language dicts from which ever folder and file they are, for me its the same folder and different files...
from .he import he
from .en import en
class NestedNamespace(SimpleNamespace):
def __init__(self, dictionary, **kwargs):
super().__init__(**kwargs)
for key, value in dictionary.items():
if isinstance(value, dict):
self.__setattr__(key, NestedNamespace(value))
else:
self.__setattr__(key, value)
text = {}
text.update({"he": NestedNamespace(he)})
text.update({"en": NestedNamespace(en)})
print(text['he'].menu.menu1) #works
使用namedtuple的选项2(我认为这个比较慢,根据我读到的有关namedtuple的制作方式,但我不是专业人士,所以选择你喜欢的任何东西):
from collections import namedtuple
def customDictDecoder(dict1):
for key, value in dict1.items():
if type(value) is dict:
dict1[key] = customDictDecoder(value)
return namedtuple('X', dict1.keys())(*dict1.values())
text = {}
text.update({"he": customDictDecoder(he)})
text.update({"en": customDictDecoder(en)})
print(text['he'].menu.menu2) #works
如果你想让print(text.he.menu.menu1) 工作,这是可能的,但我看不出它的用途,如果你想要,请告诉我