|
import argparse |
|
import shutil |
|
import re |
|
|
|
def replace_characters_between_strings(filename, copyname, stringA, stringB, replacements, encoding='utf-8'): |
|
|
|
shutil.copyfile(filename, copyname) |
|
|
|
|
|
with open(filename, 'r', encoding=encoding) as input_file: |
|
|
|
with open(copyname, 'w', encoding=encoding) as output_file: |
|
inside_text = False |
|
|
|
|
|
for line in input_file: |
|
if re.search(re.escape(stringA), line): |
|
inside_text = True |
|
|
|
|
|
if inside_text: |
|
for char_to_replace, replacement_char in replacements: |
|
line = line.replace(char_to_replace, replacement_char) |
|
|
|
output_file.write(line) |
|
|
|
if re.search(re.escape(stringB), line): |
|
inside_text = False |
|
|
|
|
|
parser = argparse.ArgumentParser(description='Replace user-defined characters between user-defined strings in a file.') |
|
parser.add_argument('filename', type=str, nargs='?', help='the name of the input file') |
|
parser.add_argument('copyname', type=str, nargs='?', help='the name of the copy file') |
|
parser.add_argument('stringA', type=str, nargs='?', help='the starting string') |
|
parser.add_argument('stringB', type=str, nargs='?', help='the ending string') |
|
parser.add_argument('replacements', nargs='*', metavar=('char_to_replace', 'replacement_char'), help='character replacements (e.g., a b c d)') |
|
parser.add_argument('--encoding', type=str, default='utf-8', help='the file encoding (default: utf-8)') |
|
args = parser.parse_args() |
|
|
|
|
|
if not args.filename: |
|
args.filename = input("Enter the name of the input file: ") |
|
if not args.copyname: |
|
args.copyname = input("Enter the name of the output file: ") |
|
if not args.stringA: |
|
args.stringA = input("Enter the starting string: ") |
|
if not args.stringB: |
|
args.stringB = input("Enter the ending string: ") |
|
if not args.replacements: |
|
args.replacements = [] |
|
while True: |
|
char_to_replace = input("Enter the character to replace (or press Enter to finish): ") |
|
if not char_to_replace: |
|
break |
|
replacement_char = input("Enter the replacement character: ") |
|
args.replacements.append((char_to_replace, replacement_char)) |
|
|
|
|
|
replace_characters_between_strings(args.filename, args.copyname, args.stringA, args.stringB, args.replacements, encoding=args.encoding) |
|
|