1

我已经阅读了看起来相似的示例,但我还没有达到理解答案的水平。我想获取列表输出并将每个接口写为单独的行(aka list I write to a csv)。我需要在关键字“interface Vlan*”上拆分初始返回列表

我想将关键字接口上的返回列表 vlanlist 拆分vlan*为单独的列表

from ciscoconfparse import CiscoConfParse
import os

for filename in os.listdir():
    if filename.endswith(".cfg"):
        p = CiscoConfParse(filename)
        vlanlist=(p.find_all_children('^interface Vlan'))
        vlanlist.insert(0,filename)

        print(vlanlist) 

这是一行输出。我需要将关键字列表拆分"interface vlanxxx"为单独的行

[ 'interface Vlan1', ' no ip address', ' shutdown', 'interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']

所需的输出(这可能有 2-20 个不同的接口,我想根据配置文件进行拆分)

['interface Vlan1' ' no ip address', ' shutdown']
['interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']
4

4 回答 4

1

vlanlist在附加文件名之前,您可以进一步分隔返回的:

# First, find the index in the list where "interface Vlan" exists:
# Also, append None at the end to signify index for end of list
indices = [i for i, v in enumerate(l) if v.startswith('interface Vlan')] + [None]

# [0, 3, None]

# Then, create the list of lists based on the extracted indices and prepend with filename
newlist = [[filename] + vlanlist[indices[i]:indices[i+1]] for i in range(len(indices)-1)]

for l in newlist: print(l)

# ['test.cfg', 'interface Vlan1', ' no ip address', ' shutdown']
# ['test.cfg', 'interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']

第二个列表理解的解释:

newlist = [
    [filename] +                   # prepend single-item list of filename
    vlanlist[                      # slice vlanlist
        indices[i]:                # starting at the current index
        indices[i+1]               # up to the next index
    ] 
    for i in range(len(indices)-1) # iterate up to the second last index so i+1 doesn't become IndexError
]

如果您不喜欢索引方法,可以尝试zip

lists = [[filename] + vlanlist[start:end] for start, end in zip(indices[:-1], indices[1:])]
于 2018-10-23T16:31:34.040 回答
1

这是一个与您的单个测试用例高度耦合的解决方案。如果完整的数据集不能代表您的单个测试用例,您将不得不通过更多测试来改进它。

def extract(items):
  result, filename, idx = [], items[0], -1

  for x in items[1:]:
    if x.startswith('interface Vlan'):
      idx += 1
      result.append([filename])
    result[idx].append(x)

  return result

# given & expected are your example and output 
assert expected == extract(given)

编辑:
...您已经更改了输入和输出。

def extract(items):
  result, idx = [], -1

  for x in items:
    if x.startswith('interface Vlan'):
      idx += 1
      result.append([])

    if not result: continue  # assuming possible unwanted items before 'interface Vlan'
    result[idx].append(x)

  return result

assert expected == extract(given)
于 2018-10-23T16:26:38.350 回答
1

一个快速而直接的解决方案。检查列表中的interface Vlan项目,如果是,它会创建一个新列表,否则会附加到旧列表中,并添加一些.strip()以进行良好的衡量。

output = ['interface Vlan1', ' no ip address', ' shutdown', 'interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']

results = []

for i in output:
    if 'interface Vlan' in i:
        results.append([i.strip()])
    else:
        results[-1].append(i.strip())

>> results
 [['interface Vlan1', 'no ip address', 'shutdown'],
 ['interface Vlan2003',
  'description XXXXXX',
  'ip address 10.224.6.130 255.255.255.224',
  'no ip redirects',
  'no ip unreachables',
  'no ip proxy-arp',
  'load-interval 60',
  'arp timeout 420']]
于 2018-10-23T16:48:42.120 回答
0

这标识了一个拆分点,并将您的列表划分为指定的两个列表。split_pos 列表将查找所有拆分位置;如果有多个分割点,您可以遍历它。拆分条件查找以给定文本和至少三个字符开头的字符串,即您帖子中的“xxx”。

vlanlist = ['sw01.cfg', 'interface Vlan1', ' no ip address', ' shutdown', 'interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']
target = "interface Vlan"

split_pos = [idx for idx, str in enumerate(vlanlist) if str.startswith(target) and \
                                                        len(str) >= len(target)+3][0]

out1 = [vlanlist[0]] + vlanlist[1:split_pos]
out2 = [vlanlist[0]] + vlanlist[split_pos:]

print(out1)
print(out2)

输出:

['sw01.cfg', 'interface Vlan1', ' no ip address', ' shutdown']
['sw01.cfg', 'interface Vlan2003', ' description XXXXXX', 
 ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects',
 ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']
于 2018-10-23T16:30:42.590 回答