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.
47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
"""Core text replacement logic."""
|
|
|
|
|
|
def prepare_pairs(pairs: list[tuple[str, str]]) -> list[tuple[str, str]]:
|
|
"""Order the pairs so the longest value1 comes first.
|
|
|
|
`replace_line` relies on this ordering to select the longest match at
|
|
each position, which makes the result deterministic when configuration
|
|
values overlap (for example "b" and "bb"). Preparing the pairs once
|
|
here keeps that cost out of the per-line loop.
|
|
"""
|
|
return sorted(pairs, key=lambda pair: len(pair[0]), reverse=True)
|
|
|
|
|
|
def replace_line(line: str, pairs: list[tuple[str, str]]) -> tuple[str, int]:
|
|
"""Replace all non-overlapping matches in the line.
|
|
|
|
At each position the first matching value1 wins, so `pairs` must be
|
|
ordered by `prepare_pairs` for the longest match to be selected.
|
|
|
|
Returns the changed line and the number of symbols replaced.
|
|
"""
|
|
result = []
|
|
replaced_symbols = 0
|
|
position = 0
|
|
|
|
while position < len(line):
|
|
match = None
|
|
|
|
for value1, value2 in pairs:
|
|
if line.startswith(value1, position):
|
|
match = (value1, value2)
|
|
break
|
|
|
|
if match is None:
|
|
result.append(line[position])
|
|
position += 1
|
|
continue
|
|
|
|
value1, value2 = match
|
|
|
|
result.append(value2)
|
|
replaced_symbols += len(value1)
|
|
position += len(value1)
|
|
|
|
return "".join(result), replaced_symbols
|