Apr-28-2018, 10:32 AM
The problem is that you have more entries with "svc:1" than with "@ttml" but zip is hidding you this as it will stop when the shortest iterable is empty.
One solution can be to obtain directly the mapping as a dictionary:
If you need to keep the 2 list format for something the same idea works: do not append to the lists until you have a valid dn:
One solution can be to obtain directly the mapping as a dictionary:
import re macdn = {} with open('pppoe.txt','r') as f: dn = None for line in f: if '@ttml' in line: dn = re.findall(r'\d{10}',line)[0] if 'svc:1' in line and dn is not None: mac = re.findall(r'mac:[a-fA-F0-9]{2}[:][a-fA-AF0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}',line) if dn in macdn: macdn[dn].extend(mac) else: macdn[dn] = list(mac) dn = None for dn in macdn: print('{} {}'.format(dn, macdn[dn]))This allows for several macs with same dns. You can invert the logic easily to obtain a dictionary for one mac with several dns)
If you need to keep the 2 list format for something the same idea works: do not append to the lists until you have a valid dn:
import re dnlist = [] maclist = [] with open('pppoe.txt','r') as f: dn = None for line in f: if '@ttml' in line: dn = re.findall(r'\d{10}',line) if 'svc:1' in line and dn is not None: mac = re.findall(r'mac:[a-fA-F0-9]{2}[:][a-fA-AF0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}',line) dnlist.append(dn) maclist.append(mac) dn = None for dn, mac in zip(dnlist, maclist): print('{} {}'.format(dn, mac))Finally if you want to record all the mac you can just add the '-' to the dn list:
import re dnlist = [] maclist = [] with open('pppoe.txt','r') as f: for line in f: if line.strip() == '-': dnlist.append(['-'*10]) if '@ttml' in line: dn = re.findall(r'\d{10}',line) dnlist.append(dn) if 'svc:1' in line: mac = re.findall(r'mac:[a-fA-F0-9]{2}[:][a-fA-AF0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}',line) maclist.append(mac) for dn, mac in zip(dnlist, maclist): print('{} {}'.format(dn, mac))