提问人:SammySaucer 提问时间:2/18/2022 更新时间:2/18/2022 访问量:105
使用 Python 删除周围的文本
Remove surrounding text using Python
问:
我创建了一个 Python 脚本,用于替换文本并为文本文件中的字符添加引号。我想删除任何其他周围的文本行,这些文本通常以“set”一词开头。
这是我目前的代码:
import re
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
line = line.replace('set system host-name EX4300', 'hostname "EX4300"')
line = line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address')
line = re.sub(r'set interfaces ge-0/0/0 description (.*)', r'interface 1/1\nname "\1"', line)
line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname "\1"', line)
#and so on...
fout.write(line)
源文本文件包含如下所示的周围文本:
set system auto-snapshot
set system domain-name EX4300.lab
set system time-zone America/New_York
set system no-redirects
set system internet-options icmpv4-rate-limit packet-rate 2000
set system authentication-order tacplus
set system ports console type vt100
我想删除我在代码中没有调用的任何其他文本。
我尝试将其添加到代码底部,但没有成功:
for aline in fin:
new_data = aline
if new_data.startswith("set"):
new_data = ""
答:
0赞
Timmy Diehl
2/18/2022
#1
我要做的是读取文件,创建一个包含所有信息的字符串,然后将其写入不同的文件。它会是这样的:
import re
with open("SanitizedFinal_E4300.txt", "r") as f:
read = f.read()
info = ""
for line in read.split("\n"):
og_line = line
line = line.replace('set system host-name EX4300', 'hostname "EX4300"')
line = line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address')
line = re.sub(r'set interfaces ge-0/0/0 description (.*)', r'interface 1/1\nname "\1"', line)
line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname "\1"', line)
if "set" in line and line == og_line: # line == og_line makes sure that "line" wasn't changed at all
line = ""
if line != "":
info += line + "\n"
with open("output6.txt", "w+") as f:
f.write(info)
评论
line = line.replace('set system host-name EX4300', 'hostname "EX4300"')