如何将跨多行的端口VLAN解析表数据转换为Python字典?
交换机端口VLAN解析表转Python字典列表
需求说明
将包含跨多行Trunk VLANs字段的交换机端口VLAN表数据,转换为以表头为键、对应列数据为值的Python字典列表。
输入数据
Port Native VLAN Trunk VLANs ------------------------------------------------------------------------- 1/1/2 1 1-2,77,90,802,998-999 1/1/4 2 2,10,12-15,25,30,44,555,802 1/1/5 None 10,555 1/1/6 2 2,10,12-15,25-26,30,44,77,80,90,150,190,260,555, 767,802,997-999,1379 1/1/7 None 10,555 1/1/8 2 2,10,12-15,25,30,44,555,802 1/1/9 2 2,10,12-15,25-26,30,44,77,80,90,150,190,260,555, 767,802,997-999,1379
期望输出
[ {'Port': '1/1/2', 'Native VLAN': '1', 'Trunk VLANs': '1-2,77,90,802,998-999'}, {'Port': '1/1/4', 'Native VLAN': '2', 'Trunk VLANs': '2,10,12-15,25,30,44,555,802'}, {'Port': '1/1/5', 'Native VLAN': 'None', 'Trunk VLANs': '10,555'}, {'Port': '1/1/6', 'Native VLAN': '2', 'Trunk VLANs': '2,10,12-15,25-26,30,44,77,80,90,150,190,260,555,767,802,997-999,1379'}, {'Port': '1/1/7', 'Native VLAN': 'None', 'Trunk VLANs': '10,555'}, {'Port': '1/1/8', 'Native VLAN': '2', 'Trunk VLANs': '2,10,12-15,25,30,44,555,802'}, {'Port': '1/1/9', 'Native VLAN': '2', 'Trunk VLANs': '2,10,12-15,25-26,30,44,77,80,90,150,190,260,555,767,802,997-999,1379'} ]
实现代码
def parse_vlan_table(data): # 清理输入行:去掉空行和首尾空格 lines = [line.strip() for line in data.split('\n') if line.strip()] # 定义表头键名 headers = ['Port', 'Native VLAN', 'Trunk VLANs'] result = [] current_entry = None # 跳过表头和分隔线,从第三行开始遍历数据行 for line in lines[2:]: # 判断是否是新端口条目(以数字/斜杠开头) if line.startswith(tuple('0123456789')): # 如果有未完成的条目,先处理并加入结果列表 if current_entry: current_entry['Trunk VLANs'] = current_entry['Trunk VLANs'].replace(', ', ',').strip(',') result.append(current_entry) # 拆分新行数据,初始化当前条目 parts = line.split(maxsplit=2) current_entry = { headers[0]: parts[0], headers[1]: parts[1], headers[2]: parts[2] if len(parts) > 2 else '' } else: # 把当前行内容追加到Trunk VLANs字段 current_entry['Trunk VLANs'] += ' ' + line.strip() # 处理最后一个未完成的条目 if current_entry: current_entry['Trunk VLANs'] = current_entry['Trunk VLANs'].replace(', ', ',').strip(',') result.append(current_entry) return result # 测试用输入数据 input_data = """Port Native VLAN Trunk VLANs ------------------------------------------------------------------------- 1/1/2 1 1-2,77,90,802,998-999 1/1/4 2 2,10,12-15,25,30,44,555,802 1/1/5 None 10,555 1/1/6 2 2,10,12-15,25-26,30,44,77,80,90,150,190,260,555, 767,802,997-999,1379 1/1/7 None 10,555 1/1/8 2 2,10,12-15,25,30,44,555,802 1/1/9 2 2,10,12-15,25-26,30,44,77,80,90,150,190,260,555, 767,802,997-999,1379 """ # 执行解析并格式化输出 output = parse_vlan_table(input_data) import pprint pprint.pprint(output)
代码逻辑说明
- 数据清理:先过滤掉空行,去除每行首尾多余空格;
- 条目识别:通过行首是否为数字判断是否是新的端口条目,初始化对应的字典;
- 跨多行合并:如果当前行不是新条目,就将内容追加到当前条目的
Trunk VLANs字段; - 格式修正:最后清理
Trunk VLANs字段内的多余空格和逗号,保证格式统一。
内容的提问来源于stack exchange,提问作者Sandy
相关产品推荐
相关产品推荐

