要搜索的字符串:
filecontent = policy-map PM_QOS_C_V-50-50-0-0
class CM_QOS_C_VOICE
priority level 1
police cir percent 9
class CM_QOS_C_VIDEO
priority level 2 percent 15
class CM_QOS_C_ROUTING
bandwidth remaining percent 1
police cir percent 6
class CM_QOS_C_NETMGT
bandwidth remaining percent 1
police cir percent 6
set mpls experimental topmost 7
class CM_QOS_C_CALLSIG
bandwidth remaining percent 1
set mpls experimental topmost 7
police cir percent 6
class CM_QOS_C_SRV
bandwidth remaining percent 7
queue-limit 4096 packets
police cir percent 20
class CM_QOS_C_PRIORITY
bandwidth remaining percent 7
queue-limit 64 packets
police cir percent 30
....
qos = {'VOICE': {'remainingbwspeed': 990.0,
'remainingpercent': 22,
'string': '#VOICE#'},
'VIDEO': {'remainingbwspeed': 405.0,
'remainingpercent': 9,
'string': '#VIDEO#'}}....
我想遍历提取的文本文件,并用"new"值替换文本文件中的"percent"值。到目前为止我做到了:
- 逐行打开文件,在字典中找到关键字并打印下一行
我找不到的东西:
- 打开文件,遍历文件直到第一个键,跳到第一个百分比,然后替换带宽剩余值
到目前为止我使用的代码:[string above is contents of file,snippit]
with open("./playbooks/qos/policy_map_PM_QOS_C_V-50-50-0-0.cfg", "r") as file:
for i, line in enumerate(file):
for key, value in qos.items():
pattern = re.compile(key)
for match in re.finditer(pattern, line):
print(line)
line1=file.readline()
line2=file.readline()
print(line1)
print(line2)
但这似乎把迭代器搞砸了。
我会这样做(只要正则表达式是字符串(:
with open("./playbooks/qos/policy_map_PM_QOS_C_V-50-50-0-0.cfg", "r") as file:
line = True
while line:
line = file.readline()
for key in qos.keys():
if key in line:
print(line)
line1=file.readline()
line2=file.readline()
print(line1)
print(line2)
break # otherwise it'll continue checking the other keys after one is found, if you want that functionality then remove this break