i18n.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import json
  2. from pathlib import Path
  3. class Addition:
  4. @classmethod
  5. def load_additions(cls) -> dict:
  6. result = {}
  7. files: str = ['en-US', 'zh-CN']
  8. for file in files:
  9. file_path = Path.cwd() / 'assets' / 'i18n' / f'{file}.json'
  10. result[file] = {}
  11. if not file_path.exists():
  12. continue
  13. with open(str(file_path), 'r', encoding='utf-8') as f:
  14. result[file] = json.load(f)
  15. return result
  16. class I18n(Addition):
  17. file_zh_cn = Path.cwd() / 'module' / 'config' / 'i18n' / 'zh-CN.json'
  18. @classmethod
  19. def trans_zh_cn(cls, text) -> str:
  20. cn_zh_data = cls.load_zh_cn()
  21. return cn_zh_data[text] if text in cn_zh_data else text
  22. @classmethod
  23. def save_zh_cn(cls, data) -> None:
  24. I18n.file_zh_cn.parent.mkdir(parents=True, exist_ok=True)
  25. with open(str(I18n.file_zh_cn), 'w', encoding='utf-8') as f:
  26. s = json.dumps(data, indent=2, ensure_ascii=False, sort_keys=False, default=str)
  27. f.write(s)
  28. @classmethod
  29. def load_zh_cn(cls) -> dict:
  30. if not I18n.file_zh_cn.exists():
  31. return {}
  32. with open(str(I18n.file_zh_cn), 'r', encoding='utf-8') as f:
  33. return json.load(f)
  34. if __name__ == '__main__':
  35. print(I18n.load_zh_cn())