Reputation: 1
So I have a pretty basic program that prompts for user input, then uses regex to look through the lines of a file and replace selected text with the values the user input.
I do currently have this working, but it's pretty clunky, with 24 lines asking for user input (I believe this is unavoidable), and another 24 lines for the Regex Substitution.
What I'd like to do, if possible, is replace those 24 Regex Lines with a single line that selects text to replace based on the variable name.
I was thinking of using an array for the variables, then using a for loop to run through them.
This is the code I'm currently using. It works fine, it just seems like a brute force method.
hostname = input("Please enter the hostname of the device: ")
switch = input("Please enter the switch that the device connects to: ")
switch_ip = input("Please enter the ip address of that switch: ")
for line in fileinput.input(inplace=1, backup='.bak'):
line = re.sub('<hostname>',hostname, line.rstrip())
line = re.sub('<switch>',switch, line.rstrip())
line = re.sub('<switch-ip>',switch_ip, line.rstrip())
print(line)
I was thinking of something like this:
hostname = input("Please enter the hostname of the device: ")
switch = input("Please enter the switch that the device connects to: ")
switch_ip = input("Please enter the ip address of that switch: ")
var_array[] = hostname, switch, switch_ip
for line in fileinput.input(inplace=1, backup='.bak'):
for v in var_array[]:
line = re.sub('<v>',v, line.rstrip())
print(line)
The important thing though would be that the v in '' would need to have the variable name as the value, not the value of the variable itself, so the Regex works properly.
So, at var_array[0]
the line
line = re.sub('<v>',v, line.rstrip())
becomes
line = re.sub('<hostname>',hostname, line.rstrip())
I feel like this is something that should be possible, but I can't find anything on how to do this.
Any and all help appreciated.
Upvotes: 0
Views: 98
Reputation: 1470
You can just create a dict of variable names as key and values as value.
var_map = {}
var_map['hostname'] = input("Please enter the hostname of the device: ")
var_map['switch'] = input("Please enter the switch that the device connects to: ")
var_map['switch_ip'] = input("Please enter the ip address of that switch: ")
for line in fileinput.input(inplace=1, backup='.bak'):
for var, val in var_map.items():
line = re.sub(f'<{var}>', val, line.rstrip())
print(line)
Upvotes: 1