马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 菜鸟江湖 于 2020-5-26 19:31 编辑
我之前发过帖子最后还是没有解决,我用别的方式解决需求了,但是最近还是遇到问题还是需要想办法走老路解决,我想过用列表然后在读取但是太菜了没搞定,请各路大神帮忙看下怎么实现。
需求:
1、提取文本中两个"!"之间的内容(两个!之间的内容是跨行内容)
2、对提取的对象进行处理,处理完成后写入新文本
3、循环第二步,直到文本读完
4、把没有math到的部分做标记也写入新文本#txt内容为:
"""
!
spanning-tree mode mst
spanning-tree portfast bpduguard default
spanning-tree extend system-id
!
spanning-tree mst configuration
name gmcc
revision 2
instance 1 vlan 1-4094
!
spanning-tree mst 1 priority 24576
diagnostic bootup level minimal
diagnostic cns publish cisco.cns.device.diag_results
diagnostic cns subscribe cisco.cns.device.diag_commands
fabric timer 15
!
vlan internal allocation policy ascending
vlan access-log ratelimit 2000
!
vlan 2
name MMIntranet
!
vlan 3
!
vlan 4
name YiJiLouGuanLi
!
"""
#下面是我之前写的脚本,是逐行读取文本进行对象处理的
def match_1(new_filename,line_number,line):
# sys.stdout.write(" \r")
# sys.stdout.write("正在收集第"+line_number+"行!\r")
#一、全局替换"!"为"#"
match_Obj_1 = re.match(r'^(!)\n, line, re.I)
if match_Obj_1 != None:
with open(new_filename, "a", encoding="UTF-8") as file:
file.write('#'+'\n')
return
#二、替换vlan和vlan描述
match_Obj_1=re.match(r'^vlan (\d)(.*),line,re.I)
if match_Obj_1 != None :
with open(new_filename,"a",encoding="UTF-8") as file :
file.write('vlan '+match_Obj_1.group(1)+re.sub(r',','\nvlan ',(re.sub(r'-',' to ',match_Obj_1.group(2))))+'\n')
return
#十、将没有match到的line直接写入文本并添加注释"//"
with open(new_filename,"a",encoding="UTF-8") as file :
file.write("//"+line)
return
#输入需要打开的文件和输出文件的名字
old_filename=input("请输入匹配文本名字\n") + ".txt"
old_filename1=old_filename + "_1.txt"
new_filename=old_filename + "_Translator.txt"
line_number=0
#之前遇到跨行内容我想出的解决办法,直接用re.sub替换
all_line=open(old_filename,"r").read()
with open(old_filename1,"a") as file:
file.write(re.sub("switchport trunk encapsulation dot1q\n switchport mode trunk","switchport trunk encapsulation dot1q\n switchport trunk allowed vlan all\n switchport mode trunk",all_line))
#读取匹配文本
with open(old_filename1,"r",encoding="UTF-8") as file :
#把读取的每一行的数据和输入的文件名传递给 match_1
for line in file :
line_number = line_number + 1
match_1(new_filename,str(line_number),line)
print("\n脚本结束")
input()
#脚本结束
本帖最后由 Twilight6 于 2020-5-26 21:09 编辑
看不懂你需求,你代码还带替换什么,需求都没写需要替换吧?
|