9fo912 / i18n.py
pengdaqian
fix more
49226f5
raw
history blame
958 Bytes
import os
import json
class i18nTranslator:
def __init__(self):
self.translations = {}
def init(self, path):
for filename in os.listdir(path):
if filename.endswith('.json'):
language = filename.split('.')[0]
with open(os.path.join(path, filename), 'r') as file:
self.translations[language] = json.load(file)
def trans(self, key, lng):
if lng in self.translations and key in self.translations[lng]:
return self.translations[lng][key]
elif 'en' in self.translations and key in self.translations['en']:
return self.translations['en'][key]
else:
return key
# Usage example
if __name__ == '__main__':
translator = i18nTranslator()
translator.init(path='locales')
print(translator.trans(key="Enter your prompt", lng="zh-CN")) # Output: "่พ“ๅ…ฅไฝ ็š„ๆ็คบ่ฏ(ไฝ ๅธŒๆœ›็”Ÿๆˆ็š„ๅ›พ็‰‡็š„ๆ่ฟฐ)"