translate.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import argparse
  2. import json
  3. import os
  4. def list_file_paths(path):
  5. file_paths = []
  6. for root, dirs, files in os.walk(path):
  7. if "node_modules" in dirs:
  8. dirs.remove("node_modules")
  9. if "build" in dirs:
  10. dirs.remove("build")
  11. if "i18n" in dirs:
  12. dirs.remove("i18n")
  13. for file in files:
  14. file_path = os.path.join(root, file)
  15. if file_path.endswith("png") or file_path.endswith("ico") or file_path.endswith("db") or file_path.endswith("exe"):
  16. continue
  17. file_paths.append(file_path)
  18. for dir in dirs:
  19. dir_path = os.path.join(root, dir)
  20. file_paths += list_file_paths(dir_path)
  21. return file_paths
  22. def replace_keys_in_repository(repo_path, json_file_path):
  23. with open(json_file_path, 'r', encoding="utf-8") as json_file:
  24. key_value_pairs = json.load(json_file)
  25. pairs = []
  26. for key, value in key_value_pairs.items():
  27. pairs.append((key, value))
  28. pairs.sort(key=lambda x: len(x[0]), reverse=True)
  29. files = list_file_paths(repo_path)
  30. print('Total files: {}'.format(len(files)))
  31. for file_path in files:
  32. replace_keys_in_file(file_path, pairs)
  33. def replace_keys_in_file(file_path, pairs):
  34. try:
  35. with open(file_path, 'r', encoding="utf-8") as file:
  36. content = file.read()
  37. for key, value in pairs:
  38. content = content.replace(key, value)
  39. with open(file_path, 'w', encoding="utf-8") as file:
  40. file.write(content)
  41. except UnicodeDecodeError:
  42. print('UnicodeDecodeError: {}'.format(file_path))
  43. if __name__ == "__main__":
  44. parser = argparse.ArgumentParser(description='Replace keys in repository.')
  45. parser.add_argument('--repository_path', help='Path to repository')
  46. parser.add_argument('--json_file_path', help='Path to JSON file')
  47. args = parser.parse_args()
  48. replace_keys_in_repository(args.repository_path, args.json_file_path)