1
0

remove_duplicate_chars.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 自动去除 other_characters 文件中的重复字符,只保留重复字符中的第一个
  5. """
  6. import os
  7. import shutil
  8. def remove_duplicate_characters(file_path):
  9. """
  10. 去除文件中每行的重复字符,只保留第一个出现的字符
  11. Args:
  12. file_path: 文件路径
  13. Returns:
  14. tuple: (是否修改过, 修改的行数)
  15. """
  16. modified = False
  17. modified_lines = 0
  18. try:
  19. # 创建备份
  20. # backup_path = file_path + '.backup'
  21. # shutil.copy2(file_path, backup_path)
  22. # print(f"已创建备份文件:{backup_path}")
  23. with open(file_path, 'r', encoding='utf-8') as f:
  24. lines = f.readlines()
  25. new_lines = []
  26. for line_num, line in enumerate(lines, 1):
  27. original_line = line.strip()
  28. if not original_line:
  29. new_lines.append(line)
  30. continue
  31. # 去除重复字符,只保留第一个
  32. seen_chars = set()
  33. new_line_chars = []
  34. for char in original_line:
  35. if char not in seen_chars:
  36. seen_chars.add(char)
  37. new_line_chars.append(char)
  38. else:
  39. modified = True
  40. new_line = ''.join(new_line_chars) + '\n'
  41. new_lines.append(new_line)
  42. if len(new_line_chars) != len(original_line):
  43. modified_lines += 1
  44. print(f"第 {line_num} 行:去除 {len(original_line) - len(new_line_chars)} 个重复字符")
  45. # 写入修改后的内容
  46. with open(file_path, 'w', encoding='utf-8') as f:
  47. f.writelines(new_lines)
  48. except UnicodeDecodeError as e:
  49. print(f"错误:无法读取文件 {file_path},编码问题:{e}")
  50. return False, 0
  51. except FileNotFoundError:
  52. print(f"错误:文件 {file_path} 不存在")
  53. return False, 0
  54. except Exception as e:
  55. print(f"错误:处理文件时发生异常:{e}")
  56. return False, 0
  57. return modified, modified_lines
  58. def main():
  59. file_path = 'original/references/other_characters'
  60. print("正在去除文件中的重复字符...")
  61. print(f"文件路径:{file_path}")
  62. print("-" * 50)
  63. if not os.path.exists(file_path):
  64. print(f"错误:文件 {file_path} 不存在")
  65. return 1
  66. modified, modified_lines = remove_duplicate_characters(file_path)
  67. if not modified:
  68. print("✅ 文件中没有需要去除的重复字符")
  69. else:
  70. print(f"✅ 已完成:修改了 {modified_lines} 行,去除了重复字符")
  71. print()
  72. print("验证修改结果...")
  73. # 运行检查脚本验证
  74. import subprocess
  75. try:
  76. result = subprocess.run(['python3', 'scripts/check_duplicate_chars.py'],
  77. capture_output=True, text=True)
  78. if result.returncode == 0:
  79. print("✅ 验证通过:文件中已无重复字符")
  80. else:
  81. print("❌ 验证失败:文件中仍有重复字符")
  82. print(result.stdout)
  83. return 1
  84. except Exception as e:
  85. print(f"警告:无法运行验证脚本:{e}")
  86. return 0
  87. if __name__ == "__main__":
  88. exit(main())