gpt4 book ai didi

python - 根据可能出现多次的关键词拆分列表

转载 作者:行者123 更新时间:2023-11-30 22:05:38 24 4
gpt4 key购买 nike

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

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

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),我想根据配置文件进行拆分)

['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']

最佳答案

在附加文件名之前,您可以进一步分隔返回的 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:])]

关于python - 根据可能出现多次的关键词拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52953391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com