Python,在文本文件中查找行,然后跳转到下一个'string-to-find'

问题描述

搜索的字符串:

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#'}}....

我想遍历获取的文本文件并将文本文件中的“百分比”值替换为“新”值。 我到目前为止:

  • 按行打开文件,在字典中找到关键字并打印下一行。

我找不到的:

到目前为止我使用的代码:[上面的字符串是文件内容,片段]

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