如何使用Python中的正则表达式方法将文本文件拆分为具有自定义名称(而不是计数器)的多个文本文件

2024-09-28 21:52:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有人能帮我应对这个挑战

我有一个包含以下文件的文件夹:

switch01.txt
switch02.txt

每个文件都有以下内容:

show running-config

Building configuration...

Current configuration : 23611 bytes
!
! Last configuration change at 16:15:20 BST Tue Apr 27 2021 by admin
! NVRAM config last updated at 16:15:33 BST Tue Apr 27 2021 by admin


show version

Cisco IOS Software, C3750 Software (C3750-IPSERVICESK9-M), Version 15.0(2)SE11, RELEASE SOFTWARE (fc3)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2017 by Cisco Systems, Inc.
Compiled Sat 19-Aug-17 09:28 by prod_rel_team

ROM: Bootstrap program is C3750 boot loader

show inventory

Interface              IP-Address      OK? Method Status                Protocol
Vlan1                  192.168.77.40   YES manual up                    up      
GigabitEthernet1/0/1   unassigned      YES unset  up                    up      
GigabitEthernet1/0/2   unassigned      YES unset  up                    up      
GigabitEthernet1/0/3   unassigned      YES unset  up                    up      

我想用分隔符“show+where”分割文件夹中的每个文件,并用该分隔符命名每个文件。在本例中,每个文件都有3个分隔符:show running config、show version和show inventory

拆分后,应如下所示:

文件夹内容:

switch01$$$show running-config$$$.txt
switch01$$$show version$$$.txt
switch01$$$show inventory$$$.txt
switch02$$$show running-config$$$.txt
switch02$$$show version$$$.txt
switch02$$$show inventory$$$.txt

switch01$$$的内容显示正在运行的配置$$$.txt文本文件:

Building configuration...

Current configuration : 23611 bytes
!
! Last configuration change at 16:15:20 BST Tue Apr 27 2021 by admin
! NVRAM config last updated at 16:15:33 BST Tue Apr 27 2021 by admin

switch01$$$的内容显示版本$$$.txt文本文件:

Cisco IOS Software, C3750 Software (C3750-IPSERVICESK9-M), Version 15.0(2)SE11, RELEASE SOFTWARE (fc3)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2017 by Cisco Systems, Inc.
Compiled Sat 19-Aug-17 09:28 by prod_rel_team

ROM: Bootstrap program is C3750 boot loader

switch01$$$的内容显示库存$$$.txt文本文件:

Interface              IP-Address      OK? Method Status                Protocol
Vlan1                  192.168.77.40   YES manual up                    up      
GigabitEthernet1/0/1   unassigned      YES unset  up                    up      
GigabitEthernet1/0/2   unassigned      YES unset  up                    up      
GigabitEthernet1/0/3   unassigned      YES unset  up                    up      

switch02.txt也是如此

我将这段代码拼凑在一起,使用计数器对每个文件进行唯一命名:

    if filename.endswith(".txt"):
        with open(filename,'r') as file:
            output = file.read()
            for command in output:
                splitter = re.split('show\s(?:running-config|version|inventory)',output, flags=re.IGNORECASE)
                counter=0
                for item in splitter:
                    with open(filename.replace(".txt","")+'$$$'+str(counter)+'$$$'+'.txt', 'w') as f:
                        f.write("%s\n" % item)
                        counter = counter + 1

这使文件看起来像这样:

switch01$$$0$$$.txt
switch01$$$1$$$.txt
switch01$$$2$$$.txt
switch01$$$3$$$.txt

同样在这一点上,switch01$$$0$$$.txt是空的,不需要

用正则表达式中使用的分隔符命名每个文件需要做什么


Tags: 文件txtconfigbyshowrunningconfigurationyes
1条回答
网友
1楼 · 发布于 2024-09-28 21:52:26

使用lark,您可以将switch*.txt转换为json数据,然后按照您想要的方式进行处理

% ls
s.lark      s.py        switch01.txt    switch02.txt
% cat s.lark
start : so+

so: action details+

action: /show [a-z-]+/
details: /.+/

%import common.WS
%ignore WS
% cat s.py
import json
from typing import List

import lark
from lark import Lark, Transformer

import sys


class TreeToJson(Transformer):

    def so(self, s):
        d = []
        for i in s[1:]:
            d.append(i)
        r = {"action": s[0]}

        r.update({"details": "\n".join(d)})
        return r


    def action(self, s):
        return s[0].value

    def details(self, s: List[lark.Token]):
        for i in s:
            return i


if __name__ == '__main__':

    with open(sys.argv[1]) as f:
        text = f.read()

    with open("s.lark", 'r') as grammar:
        parser = Lark(grammar, parser='lalr')
        tree = parser.parse(text)


        # uncomment this to see the tree in pretty view
        # print(tree.pretty(indent_str="    "))

        a: lark.Tree = TreeToJson().transform(tree)
        print(json.dumps(a.children, indent=4))
% python3 s.py switch01.txt
[
    {
        "action": "show running-config",
        "details": "Building configuration...\nCurrent configuration : 23611 bytes\n!\n! Last configuration change at 16:15:20 BST Tue Apr 27 2021 by admin\n! NVRAM config last updated at 16:15:33 BST Tue Apr 27 2021 by admin"
    },
    {
        "action": "show version",
        "details": "Cisco IOS Software, C3750 Software (C3750-IPSERVICESK9-M), Version 15.0(2)SE11, RELEASE SOFTWARE (fc3)\nTechnical Support: http://www.cisco.com/techsupport\nCopyright (c) 1986-2017 by Cisco Systems, Inc.\nCompiled Sat 19-Aug-17 09:28 by prod_rel_team\nROM: Bootstrap program is C3750 boot loader"
    },
    {
        "action": "show inventory",
        "details": "Interface              IP-Address      OK? Method Status                Protocol\nVlan1                  192.168.77.40   YES manual up                    up      \nGigabitEthernet1/0/1   unassigned      YES unset  up                    up      \nGigabitEthernet1/0/2   unassigned      YES unset  up                    up      \nGigabitEthernet1/0/3   unassigned      YES unset  up                    up     "
    }
]
% python3 s.py switch02.txt
[
    {
        "action": "show running-config",
        "details": "Building configuration...\nCurrent configuration : 23611 bytes\n!\n! Last configuration change at 16:15:20 BST Tue Apr 27 2021 by admin\n! NVRAM config last updated at 16:15:33 BST Tue Apr 27 2021 by admin"
    },
    {
        "action": "show version",
        "details": "Cisco IOS Software, C3750 Software (C3750-IPSERVICESK9-M), Version 15.0(2)SE11, RELEASE SOFTWARE (fc3)\nTechnical Support: http://www.cisco.com/techsupport\nCopyright (c) 1986-2017 by Cisco Systems, Inc.\nCompiled Sat 19-Aug-17 09:28 by prod_rel_team\nROM: Bootstrap program is C3750 boot loader"
    },
    {
        "action": "show inventory",
        "details": "Interface              IP-Address      OK? Method Status                Protocol\nVlan1                  192.168.77.40   YES manual up                    up      \nGigabitEthernet1/0/1   unassigned      YES unset  up                    up      \nGigabitEthernet1/0/2   unassigned      YES unset  up                    up      \nGigabitEthernet1/0/3   unassigned      YES unset  up                    up     "
    }
]

相关问题 更多 >