Multi Language Support In Python Script
Solution 1:
see python gettext module for i18n support
Solution 2:
If you only have a few languages, and don't want to use some i18n stuff, try one of these:
example (I'm just using a dict in a py file, let me know if you want specifically json):
also, this is written in python 3, not 2.
in en.py
en = {
"eng": "english",
"heb": "hebrew",
"menu": {
"menu1": "one",
"menu2": "two"
}
}
in he.py
he = {
"eng": "אנגלית",
"heb": "עברית",
"menu": {
"menu1": "אחד",
"menu2": "שתיים"
}
}
option 1 using SimpleNamespace:
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
classNestedNamespace(SimpleNamespace):
def__init__(self, dictionary, **kwargs):
super().__init__(**kwargs)
for key, value in dictionary.items():
ifisinstance(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
option 2 using namedtuple (i think this one is slower, by what i read about the way namedtuples are made, but im no pro, so choose whatever you like):
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
if you want print(text.he.menu.menu1)
to work, it is possible, but i dont see the use for it, if you want it, let me know
Solution 3:
I had this problem a while ago and just solved it by creating two arrays with the words of the two languages I needed.
# array with english wordsengList = ["dog", "cat"]
# array with german wordsgerList = ["Hund", "Katze"]
Then I just set another array to the needed language array and use the words from this array.
# referenced array set to the english array
langList = engList
print(langList[0],"+",langList[1])
# change to the german array when needed
langList = gerList
print(langList[0],"+",langList[1])
Of course it's no way near to be perfect, but it worked for me. Hope I could help!
Solution 4:
A more 'pythonic way' could be if you just make a different .py and make a new class there with if statements for each language:
classLocale:
def__init__(self, loc):
if loc == "en":
self.string = "something in English"elif loc == "fr":
self.string = "something in French"
Post a Comment for "Multi Language Support In Python Script"