#python #regex #dictionary #nested
#python #регулярное выражение #словарь #вложенный
Вопрос:
text = """sh forwarding distribution multicast route vrf A group 228.0.0.0 source 209.0.10.145
(40.45.1.2/32, 235.200.3.80/32), RPF Interface: Ethernet2/24/2, flags: L
Received Packets: 8460 Bytes: 6871184
Number of Outgoing Interfaces: 3
Outgoing Interface List Index: 243
Ethernet2/22/2
Ethernet6/7/1.11
Vlan 100
(41.45.1.2/32, 235.200.3.80/32), RPF Interface: Ethernet2/24/2, flags: L
Received Packets: 8460 Bytes: 6871184
Number of Outgoing Interfaces: 3
Outgoing Interface List Index: 243
Ethernet2/22/2
Ethernet6/7/1.10
Ethernet6/7/1.11
(43.45.1.2/32, 235.200.3.80/32), RPF Interface: Ethernet2/24/2, flags: L
Received Packets: 8460 Bytes: 6871184
Number of Outgoing Interfaces: 3
Outgoing Interface List Index: 243
Ethernet2/22/2
Ethernet6/7/1.10
Ethernet6/7/1.11"""
#expected output : Result={s1g1:{“rpf”:Eth12/24/2, ”oiflistIndex”:243,” “oiflists”:[Eth2/22/2,Eth6/7/1.10,Eth6/7/1.11]},s2g2:{……..}…}
#code i tried..
import re
tup_list = []
intf_list = []
dict_1 = {}
result = {'s1g1':{},'s2g2':{},'s3g3':{}}
p1 = re.findall(r'([d /.*].*|Received Packets:.d |Number of Outgoing Interfaces:.d |Outgoing Interface List Index:.d |[n]Ethernet. [d.*] |Vlan.[d ] ', text, re.MULTILINE)
print("matched patterns",p1)
for i in range(0,len(p1)):
p1[i] = re.sub("n", "",p1[i])
if 'RPF' in p1[i]:
tmp = p1[i].split(',')[2]
tup = ('rpf', tmp.split(':')[1])
tup_list.append(tup)
elif ':' in p1[i]:
tup = (p1[i].split(':')[0], p1[i].split(':')[1])
tup_list.append(tup)
elif ('Ethernet' in p1[i]) or ('Vlan' in p1[i]):
intf_list.append(p1[i])
print("intf list ",intf_list)
tup = ('OutIntflist', intf_list)
tup_list.append(tup)
print("ivide ",tup_list)
for k,v in tup_list:
dict_1.setdefault(k, v)
print("dict_1 ",dict_1)
for k in result:
result[k] = dict_1
print("nnResult : ",result)
Ответ №1:
import re
regex = r"([d /.*].*|Received Packets:.d |Number of Outgoing Interfaces:.d |Outgoing Interface List Index:.d |bEthernet. [d.*] |Vlan.[d ] "
test_str = ("sh forwarding distribution multicast route vrf A group 228.0.0.0 source 209.0.10.145 n"
"(40.45.1.2/32, 235.200.3.80/32), RPF Interface: Ethernet2/24/2, flags: L n"
"Received Packets: 8460 Bytes: 6871184 n"
"Number of Outgoing Interfaces: 3 n"
"Outgoing Interface List Index: 243 n"
"Vlan 100 n"
"Vlan 100 n"
"Ethernet2/22/2 n"
"Ethernet6/7/1.11 n"
"Vlan 100 n"
"(41.45.1.2/32, 235.200.3.80/32), RPF Interface: Ethernet2/24/2, flags: L n"
"Received Packets: 8462 Bytes: 6871184n"
"Number of Outgoing Interfaces: 2n"
"Outgoing Interface List Index: 264 n"
"Ethernet2/22/2 n"
"Ethernet6/7/1.11n"
"(43.45.1.2/32, 235.200.3.80/32), RPF Interface: Ethernet2/24/2, flags: L n"
"Received Packets: 8463 Bytes: 6871184 n"
"Number of Outgoing Interfaces: 2 n"
"Outgoing Interface List Index: 243 n"
"Ethernet2/22/2 n"
"Ethernet6/7/1.10")
matches = re.findall(regex, test_str, re.MULTILINE)
sg_pattern = r"(d.* )" #(pattern to get (S,G))
record = []
keys_list = []
values_list = list()
dict_1 = {}
new = []
list_rec = []
for i in range(0, len(matches)):
record.append(matches[i])
if('(' in matches[i] ):
keys_list.append(" ".join(matches[i].split(',')[0:2]))
print("keys list : ",keys_list)
print("nrecords : ",record)
# Find the position and split them as each records
pos = [i for i, item in enumerate(record) if re.search(r"(d.* )", item)]
pos.append(len(record)-1) # get end of list
#print(pos)
my_iter = iter(pos)
for i in range(0, len(pos)-1):
start_pos = pos[i]
i = i 1
end_pos = pos[i] 1
list_rec.append(record[start_pos:end_pos])
#print(start_pos, end_pos)
#print("nlist record 1 : ", list_rec)
"""Create dictionary from each record, first create tuple and then create the inner dictionary"""
n = len(list_rec)
for j in range(0,n):
intf_list = []
tup_list = []
for i in range(0, len(list_rec[j])):
if 'RPF' in list_rec[j][i]:
tmp = list_rec[j][i].split(',')[2]
tup = ('rpf', tmp.split(':')[1])
tup_list.append(tup)
elif ':' in list_rec[j][i]:
tup = (list_rec[j][i].split(':')[0], list_rec[j][i].split(':')[1])
tup_list.append(tup)
elif ('Ethernet' in list_rec[j][i]) or ('Vlan' in list_rec[j][i]):
intf_list.append(list_rec[j][i])
#print("intf list ",intf_list)
tup = ('OutIntflist', intf_list)
tup_list.append(tup)
new.append(tup_list)
#print("tup list ",tup_list)
#print("nnew", new)
for i in range(0, len(new)):
#print("new[{i}]".format(i=i),new[i])
for k,v in new[i]:
dict_1.setdefault(k, v)
#print(dict_1)
values_list.append([dict_1])
dict_1 = {}
#print(values_list)
zip_iterator = zip(keys_list, values_list)
result = dict(zip_iterator)
print("nOutput is : n", result)
Комментарии:
1. Результат — это : ============== {‘(40.45.1.2/32 235.200.3.80/32)’: [{‘ rpf’: ‘Ethernet2/24/2’, ‘Принятые пакеты’: ‘8460’, ‘Количество исходящих интерфейсов’: ‘3’, ‘Индекс списка исходящих интерфейсов’: ‘243’, ‘OutIntflist’: [‘Vlan 100’, ‘Vlan 100’, ‘Ethernet2/22/2’, ‘Ethernet6/7/1.11’, ‘Vlan 100’]}], ‘(41.45.1.2/32 235.200.3.80/32)’: [{‘ rpf’: ‘Ethernet2/24/2’, ‘Принятые пакеты’: ‘8462’, ‘Количество исходящих интерфейсов’: ‘2’, ‘Индекс списка исходящих интерфейсов’: ‘264’, ‘OutIntflist’: [‘Ethernet2/22/2’, ‘Ethernet6/7/1.11’]}], …}