【问题标题】:Replace text using Python使用 Python 替换文本
【发布时间】: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


【解决方案1】:

您可以尝试使用正则表达式,即 re.sub() (https://docs.python.org/3/library/re.html#re.sub)。在您的示例中,此片段应该可以工作:

import re

fixed_line = re.sub(r'\[set interfaces\] ge-([^ ]*)[^"]*("[^"]*")',
       r'interface \1 name \2',
       '[set interfaces] ge-0/0/0 [description] "OoB Mgmt Connection"'
       )

在哪里: r'[设置接口] ge-([^ ])[^"]("[^"]*")' 定义要捕获的模式,带有两个捕获组(在圆括号中)。然后将匹配的字符串替换为字符串接口\1名称\2,其中\1和\2是对捕获组的引用。

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多