-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranslationModule.py
More file actions
89 lines (68 loc) · 2.56 KB
/
TranslationModule.py
File metadata and controls
89 lines (68 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# import TranslationModule as tm
# from TranslationModule import TranslatedString as tStr
#
# tm.create_key(key="hello", default="en")
# tm.add_translation(key="hello", lang="ru", translation="привет")
#
# -----------
# name = "Igor"
# print(tStr(f"$'hello'$, {name}!"))
#
#
import json
def create_key(key, default=None, path="translation.json"):
with open(path, "r", encoding="utf-16") as f:
try:
trnsl = json.load(f)
except json.decoder.JSONDecodeError:
print("[TranslationModule] File is empty!")
trnsl = {}
with open(path, "w", encoding="utf-16") as f:
if default is not None:
trnsl[key] = {default: key}
json.dump(trnsl, f, indent=4, ensure_ascii=True)
def add_translation(key, lang, translation, path="translation.json"):
with open(path, "r", encoding="utf-16") as f:
try:
trnsl = json.load(f)
except json.decoder.JSONDecodeError:
print("[TranslationModule] File is empty!")
trnsl = {}
with open(path, "w", encoding="utf-16") as f:
trnsl.setdefault(key, {}).setdefault(lang, []).append(translation)
trnsl[key][lang] = translation
json.dump(trnsl, f, indent=4, ensure_ascii=True)
class TranslatedString:
def __init__(self, string_to_translate: str, lang, path="translation.json"):
self.string_to_translate = string_to_translate
self.lang = lang
self.path = path
return
def t(self) -> str:
stt = self.string_to_translate
if "$/" in stt:
stt = stt.split("$/")
stt = [val for val in stt if val != ""]
keys = []
for val in stt:
if "/" in val:
keys.append(val[0:val.index("/")])
with open(self.path, "r", encoding="utf-16") as f:
try:
trnsl = json.load(f)
except json.decoder.JSONDecodeError:
print("[TranslationModule] File is empty!")
trnsl = {}
for key in keys:
converted = trnsl[key][self.lang]
self.string_to_translate = self.string_to_translate.replace(f"$/{key}/", converted)
result = self.string_to_translate
return result
def __str__(self):
self.t()
if __name__ == "__main__":
create_key(key="menu_continue")
add_translation("menu_continue", "ru", "Продолжить")
add_translation("menu_continue", "en", "Continue")
add_translation("menu_continue", "de", "Weiter")
# print(TranslatedString("$/settings_language/:", "de").t())