i18n.py 863 B

12345678910111213141516171819202122232425262728
  1. import json
  2. from pathlib import Path
  3. class I18n:
  4. file_zh_cn = Path.cwd() / 'module' / 'config' / 'i18n' / 'zh-CN.json'
  5. @classmethod
  6. def trans_zh_cn(cls, text) -> str:
  7. cn_zh_data = cls.load_zh_cn()
  8. return cn_zh_data[text] if text in cn_zh_data else text
  9. @classmethod
  10. def save_zh_cn(cls, data) -> None:
  11. I18n.file_zh_cn.parent.mkdir(parents=True, exist_ok=True)
  12. with open(str(I18n.file_zh_cn), 'w', encoding='utf-8') as f:
  13. s = json.dumps(data, indent=2, ensure_ascii=False, sort_keys=False, default=str)
  14. f.write(s)
  15. @classmethod
  16. def load_zh_cn(cls) -> dict:
  17. if not I18n.file_zh_cn.exists():
  18. return {}
  19. with open(str(I18n.file_zh_cn), 'r', encoding='utf-8') as f:
  20. return json.load(f)
  21. if __name__ == '__main__':
  22. print(I18n.load_zh_cn())