UnstableLlama's picture
Upload cswm.py
a4f8599
raw
history blame
2.79 kB
import argparse
import shutil
import re
def replace_characters_between_strings(filename, copyname, stringA, stringB, replacements, encoding='utf-8'):
# Create a copy of the original file
shutil.copyfile(filename, copyname)
# Open the original file for reading with the specified encoding
with open(filename, 'r', encoding=encoding) as input_file:
# Open the copy for writing with the specified encoding
with open(copyname, 'w', encoding=encoding) as output_file:
inside_text = False
# Process each line in the input file
for line in input_file:
if re.search(re.escape(stringA), line):
inside_text = True
# Replace the characters in the line if inside_text is 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
# Parse command-line arguments
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()
# Prompt for missing arguments if not provided
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))
# Execute the program with the provided arguments
replace_characters_between_strings(args.filename, args.copyname, args.stringA, args.stringB, args.replacements, encoding=args.encoding)