Spaces:
Runtime error
Runtime error
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: "่พๅ ฅไฝ ็ๆ็คบ่ฏ(ไฝ ๅธๆ็ๆ็ๅพ็็ๆ่ฟฐ)" | |