1
0

process_thr.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. from pathlib import Path
  5. def process_file(input_path, output_path):
  6. """Process a single file to remove duplicate consecutive lines and round coordinates."""
  7. prev = None
  8. with open(input_path) as f_in, open(output_path, 'w') as f_out:
  9. for line in f_in:
  10. line_str = line.strip()
  11. if not line_str:
  12. continue
  13. try:
  14. parts = line_str.split()
  15. if len(parts) != 2:
  16. continue
  17. theta = round(float(parts[0]), 3)
  18. rho = round(float(parts[1]), 3)
  19. rounded_line = f"{theta:.3f} {rho:.3f}"
  20. except ValueError:
  21. continue
  22. if rounded_line == prev:
  23. continue
  24. f_out.write(rounded_line + '\n')
  25. prev = rounded_line
  26. def process_directory(input_dir, output_dir=None):
  27. """Recursively process all .thr files in the input directory."""
  28. input_path = Path(input_dir)
  29. if output_dir is None:
  30. output_path = input_path / 'processed'
  31. else:
  32. output_path = Path(output_dir)
  33. output_path.mkdir(parents=True, exist_ok=True)
  34. thr_files = list(input_path.rglob('*.thr'))
  35. if not thr_files:
  36. print(f"No .thr files found in {input_dir}")
  37. return
  38. print(f"Found {len(thr_files)} .thr files to process")
  39. for thr_file in thr_files:
  40. relative_path = thr_file.relative_to(input_path)
  41. output_file = output_path / relative_path
  42. output_file.parent.mkdir(parents=True, exist_ok=True)
  43. print(f"Processing {thr_file} -> {output_file}")
  44. process_file(thr_file, output_file)
  45. print(f"\nProcessing complete! Processed files are in: {output_path}")
  46. def main():
  47. if len(sys.argv) < 2:
  48. print(f"Usage: {sys.argv[0]} input_directory [output_directory]")
  49. print("If output_directory is not specified, files will be saved in input_directory/processed")
  50. sys.exit(1)
  51. input_dir = sys.argv[1]
  52. output_dir = sys.argv[2] if len(sys.argv) > 2 else None
  53. if not os.path.isdir(input_dir):
  54. print(f"Error: {input_dir} is not a valid directory")
  55. sys.exit(1)
  56. process_directory(input_dir, output_dir)
  57. if __name__ == "__main__":
  58. main()