【发布时间】:2022-01-17 20:00:41
【问题描述】:
我正在尝试将源文件中的文本替换为新文件。 文本的替换适用于一行,但几行之后,我无法替换位于语句中间的文本。
这里是原文。括号中的单词是我要替换的,而不更改单词周围的字符:
[set interfaces] ge-0/0/0 [description] "OoB Mgmt Connection"
这是我想要输出的:
interface x/x name"xxx"(还为“name”后面的xxx文本添加引号)
编辑:
但是输出文本替换一次,然后保留原始文本的副本:
set interfaces ge-0/0/0 description "OoB Mgmt Connection"
set interfaces ge-0/0/0 description "OoB Mgmt Connection"
interface 1/1 name "OoB Mgmt Connection"
set interfaces ge-0/0/0 enable
set interfaces ge-0/0/0 enable
interface 1/1 enable
set interfaces ge-0/0/0 unit 0 description "EX4300-mgmt-1;10.30.41.14;ge-0/0/6\\n"
set interfaces ge-0/0/0 unit 0 description "EX4300-mgmt-1;10.30.41.14;ge-0/0/6\\n"
这是我的代码:
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('set system host-name EX4300', 'hostname "EX4300"'))
fout.write(line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address'))
请让我知道我哪里出错了,或者是否有更好的方法来解决这个问题。 我正在使用 Visual Studio Code。
【问题讨论】:
-
你告诉 python 替换文字文本
set interfaces ge- description。该实际文本是否出现在文件中? -
“我无法替换位于语句中间的文本”您能否发布代码失败的语句@sammysosa
-
如果要替换三个单独的字符串,则需要三个单独的替换语句。
line.replace('set interfaces','').replace('ge-','').replace('description','name'). -
你想把
[set interfaces] ge-0/0/0 [description] "OoB Mgmt Connection"变成interface 0/0/0 name"OoB Mgmt Connection"吗?如果是这种情况,类似于line.replace("[set interfaces] ge-", "interface ").replace("[description] ", "name ")的东西应该可以工作。 -
@csjh 请查看我在问题中的更新编辑。
标签: python visual-studio-code text replace