[英]Remove surrounding text using Python
I have created a Python script that replaces text and adds quotes to characters from a text file.我创建了一个 Python 脚本,用于替换文本并为文本文件中的字符添加引号。 I would like to remove any other surrounding lines of text, which usually starts with the word "set".
我想删除任何其他周围的文本行,这些文本行通常以“set”一词开头。
Here is my current code:这是我当前的代码:
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)
The source text file contains surrounding text like this:源文本文件包含这样的周围文本:
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
I would like to remove any other text that I have not called for in the code.我想删除我没有在代码中调用的任何其他文本。
I have tried adding this to the bottom of my code with no success:我尝试将其添加到我的代码底部但没有成功:
for aline in fin:
new_data = aline
if new_data.startswith("set"):
new_data = ""
What I would do is read the file, create a string with all of the info, then write it to a different file.我要做的是读取文件,创建一个包含所有信息的字符串,然后将其写入另一个文件。 It would go something like this:
它会 go 是这样的:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.