translate.py 2.0 KB

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