Initial implementation with unit and integration tests
Reads value1=value2 pairs from a configuration file and replaces every non-overlapping occurrence of value1 with value2 in a text file, printing the resulting lines sorted by the number of symbols replaced. Overlapping patterns resolve to the longest match so the result does not depend on configuration file ordering. Ties keep their original file order.
This commit is contained in:
53
main.py
Normal file
53
main.py
Normal file
@@ -0,0 +1,53 @@
|
||||
# Technical Assignment: Replace Configured Values in a Text File
|
||||
# By: Martin Stajnko
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from config_loader import load_config
|
||||
from replacer import prepare_pairs, replace_line
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Parse CLI arguments, apply configured replacements, and print
|
||||
the resulting lines sorted by number of replaced symbols
|
||||
(most-changed first)."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Replace configured values in a text file."
|
||||
)
|
||||
parser.add_argument("config_file", help="Configuration file")
|
||||
parser.add_argument("text_file", help="Input text file")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
changed_lines = []
|
||||
|
||||
try:
|
||||
# Ordered once here rather than on every line of the text file.
|
||||
pairs = prepare_pairs(load_config(args.config_file))
|
||||
|
||||
with open(args.text_file, "r", encoding="utf-8") as file:
|
||||
for line in file:
|
||||
# Remove only the newline, preserving all other characters.
|
||||
line = line.rstrip("\r\n")
|
||||
|
||||
changed_line, replaced_symbols = replace_line(line, pairs)
|
||||
|
||||
changed_lines.append((replaced_symbols, changed_line))
|
||||
|
||||
except OSError as error:
|
||||
sys.exit(f"error: {error.filename}: {error.strerror}")
|
||||
except ValueError as error:
|
||||
# Also covers UnicodeDecodeError, which is a subclass of ValueError.
|
||||
sys.exit(f"error: {error}")
|
||||
|
||||
# Most changed first. The sort is stable and keys only on the count,
|
||||
# so lines with equal counts keep their original file order.
|
||||
changed_lines.sort(key=lambda item: item[0], reverse=True)
|
||||
|
||||
for _, line in changed_lines:
|
||||
print(line)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user