分析一个关键字的.txt文件,然后寻找子关键字?

2024-05-23 13:57:36 发布

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

很抱歉,我不知道该如何正确回答这个问题。你知道吗

我有一个脚本,从思科交换机拉配置保存到一个.txt文件,我想提取关键信息。下面是提取的.txt文件的摘录:

!
!
!
!
interface Port-channel10
!
interface GigabitEthernet0/0
 description ** Uplink to C1 **
 switchport trunk allowed vlan 95
 switchport trunk encapsulation dot1q
 switchport mode trunk
 media-type rj45
 negotiation auto
!
interface GigabitEthernet0/1
 description ** Uplink to C2 **
 switchport trunk allowed vlan 95
 switchport trunk encapsulation dot1q
 switchport mode trunk
 media-type rj45
 negotiation auto
 channel-group 10 mode auto
!
interface GigabitEthernet0/2
 description ** Downlink to NetAuto **
  switchport access vlan 95
  switchport mode access
  media-type rj45
  negotiation auto
!
interface GigabitEthernet0/3
 switchport trunk encapsulation dot1q
 media-type rj45
 negotiation auto
 channel-group 10 mode auto
!
interface GigabitEthernet1/0
 media-type rj45
 negotiation auto
!
interface GigabitEthernet1/1
 media-type rj45

我希望从上述.txt文件中提取以下信息:

  • 接口信息(所有)
  • 描述(如果存在)
  • 通道组编号(如果存在)

我希望的一个输出示例是:

interface GigabitEthernet0/0
 description ** Uplink to C1 **
interface GigabitEthernet0/1
 description ** Uplink to C2 **
 channel-group 10
interface GigabitEthernet0/2
 description ** Downlink to NetAuto **

等等。。。你知道吗

不过,下面是我当前的代码,它没有给我任何我想要的东西,我对有限的python知识完全没有想法:

with open('newfile1', 'r') as fi:
    int = []
    desc = []
    for ln in fi:
        if ln.startswith("interface"):
            int = (ln)
            print(int) 
            for ln in fi: 
                if ln.startswith(" description"): 
                    desc = (ln) 
                    print(desc) 

这将返回:

interface Port-channel10

 description ** Uplink to C1 **

 description ** Uplink to C2 **

 description ** Downlink to NetAuto **

Tags: totxtautomodetypedescriptionmediainterface
3条回答

保持简单-将文本文件拆分为行,将行拆分为单词,检查第一个单词是否在您感兴趣的单词列表中。你知道吗

results = []
first_words = ['interface', 'description', 'channel-group']
input_file = 'switch.txt'

with open(input_file, 'r') as switch_file:
    for line in switch_file.readlines():
        words_in_line = line.split()
        # There should be at least 1 word in the line
        if 0 < len(words_in_line):
            first_word = words_in_line[0]
            if any(first_word in s for s in first_words):
                results.append(line.rstrip())

print("\n".join(results))

输出:

interface Port-channel10
interface GigabitEthernet0/0
 description ** Uplink to C1 **
interface GigabitEthernet0/1
 description ** Uplink to C2 **
 channel-group 10 mode auto
interface GigabitEthernet0/2
 description ** Downlink to NetAuto **
interface GigabitEthernet0/3
 channel-group 10 mode auto
interface GigabitEthernet1/0
interface GigabitEthernet1/1

使用简单的迭代。你知道吗

例如:

result = []
with open(filename) as infile:    #Filename == Your File 
    for line in infile:           #Iterate Each line
        line = line.strip()
        if line.startswith("interface GigabitEthernet"):   #Check condition
            result.append([line])
            while True:
                try:
                    line = next(infile).strip()
                except:  #Handle StopIteration Error
                    break
                if line == "!":
                    break
                if line.startswith("description"):   #Check condition
                    result[-1].append(line)
                if line.startswith("channel-group"):   #Check condition
                    result[-1].append(line)
print(result) 

输出:

[['interface GigabitEthernet0/0', 'description ** Uplink to C1 **'],
 ['interface GigabitEthernet0/1',
  'description ** Uplink to C2 **',
  'channel-group 10 mode auto'],
 ['interface GigabitEthernet0/2', 'description ** Downlink to NetAuto **'],
 ['interface GigabitEthernet0/3', 'channel-group 10 mode auto'],
 ['interface GigabitEthernet1/0'],
 ['interface GigabitEthernet1/1']]

把数据组织好以便使用是非常重要的。我建议您使用字典来存储每个接口的详细信息。所以,从文件中提取的数据就是这样一个字典列表。相同的代码如下所示:

with open('test.txt', 'r') as file:
    data = []
    for line in file:
        if line.startswith('interface'):
            data.append(dict(interface=line.replace('interface', '').strip()))
            print(line) # check it on the console

        if line.strip().startswith('description'):
            data[-1]['description'] = line.replace('description', '').strip()
            print(line) # check it on the console

        if line.strip().startswith('channel-group'):
            data[-1]['channel-group'] = line.replace('channel-group', '').strip()
            print(line) # check it on the console

print(data) # prints a list of dicts

数据将是:

[{'interface': 'Port-channel10'}, {'interface': 'GigabitEthernet0/0', 'description': '** Uplink to C1 **'}, {'interface': 'GigabitEthernet0/1', 'description': '** Uplink to C2 **', 'channel-group': '10 mode auto'}, {'interface': 'GigabitEthernet0/2', 'description': '** Downlink to NetAuto **'}, {'interface': 'GigabitEthernet0/3', 'channel-group': '10 mode auto'}, {'interface': 'GigabitEthernet1/0'}, {'interface': 'GigabitEthernet1/1'}]

相关问题 更多 >