使用 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 ""', line)
        line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname ""', 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 = ""

我要做的是读取文件,创建一个包含所有信息的字符串,然后将其写入另一个文件。它会是这样的:

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 ""', line)
    line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname ""', 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)