因此,我有一个非常基本的程序,提示用户输入,然后使用正则表达式浏览文件的各行,并将所选文本替换为用户输入的值。
我目前确实可以使用此功能,但是它很笨拙,有24行要求用户输入(我相信这是不可避免的),另外24行用于Regex Substitution。
如果可能的话,我想用单行替换这24条正则表达式行,该行根据变量名选择要替换的文本。
我当时在考虑使用数组作为变量,然后使用for循环遍历它们。
这是我当前正在使用的代码。它工作正常,似乎只是一种蛮力方法。
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)
我在想这样的事情:
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)
但是重要的是''中的v需要以变量名作为值,而不是变量本身的值,因此Regex可以正常工作。
因此,在var_array[0]
行
line = re.sub('<v>',v, line.rstrip())
成为
line = re.sub('<hostname>',hostname, line.rstrip())
我觉得这是应该可行的,但是我找不到如何做到这一点的东西。
任何人和所有帮助表示赞赏。
答案 0 :(得分:1)
您可以只创建一个变量名作为键,值作为值的字典。
q = p;