From 024b8f23dd92e5d2c5024644563040fdae4e27fb Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Tue, 21 Mar 2023 14:01:33 -0600 Subject: [PATCH] added main, arg parsing, and string cleaner function. --- PA004/clean_file.py | 56 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100755 PA004/clean_file.py diff --git a/PA004/clean_file.py b/PA004/clean_file.py new file mode 100755 index 0000000..c8297ef --- /dev/null +++ b/PA004/clean_file.py @@ -0,0 +1,56 @@ +#!/usr/bin/python3 + +import argparse +import re + +# Constants +CONTROL_B = '\x02' +CONTROL_C = '\x03' +CARRIAGE_RET = '\r' + + +def sanitized_string(dirty_string): + cleaned_string = re.sub( + rf'{CONTROL_C}(\r{0,4}{CONTROL_C}*?)*{CONTROL_B}', + "", + dirty_string + ) + + return cleaned_string + +def main(): + parser = argparse.ArgumentParser( + description='A program to clean a file based on a specific \ + pattern' + ) + parser.add_argument( + 'input_file_path', + type=str, + help='path to a input file to be cleaned' + ) + parser.add_argument( + '-o', '--output_file_path', + type=str, + help='path to an output file if applicable', + default=None + ) + + args = parser.parse_args() + + if args.output_file_path is not None: + with (open(args.input_file_path, 'r') as input_file, + open(args.output_file_path, 'w') as output_file): + + for dirty_line in input_file: + sanitized_line = sanitized_string(dirty_line) + output_file.write(sanitized_line) + else: + with open(args.input_file_path, 'r') as input_file: + for dirty_line in input_file: + sanitized_line = sanitized_string(dirty_line) + print(sanitized_line) + + + +if __name__ == '__main__': + main()