I am trying to process a file that looks more or less like this:
f=0412345678 t=0523456789 t=0301234567 s=Party! flag=urgent flag=english id=1221AB12
I know I can for example use Python shlex to parse those without major issues with something like:
entry = "f=0412345678 t=0523456789 t=0301234567 s=Party! flag=urgent flag=english id=1221AB12"
line = shlex.split(entry)
I can then do a for loop and iterate over the key value pairs.
row = {}
for kvpairs in line:
key, value = kvpairs.split("=")
row.setdefault(key,[]).append(value)
print row
Results in:
{'id': ['1221AB12'], 's': ['Party!'], 'flag': ['urgent', 'english'], 't': ['0523456789', '0301234567'], 'f': ['0412345678']}
So far so good but I am having trouble finding an efficient way of outputting the original line so that the output looks like:
id=1221AB12 f=0412345678 t=0523456789 s=Party! flag=urgent
id=1221AB12 f=0412345678 t=0523456789 s=Party! flag=english
id=1221AB12 f=0412345678 t=0301234567 s=Party! flag=urgent
id=1221AB12 f=0412345678 t=0301234567 s=Party! flag=english
product from itertools and
from itertools import product
from collections import OrderedDict
a = OrderedDict({'id': ['1221AB12'], 's': ['Party!'], 'flag': ['urgent', 'english'], 't': ['0523456789', '0301234567'], 'f': ['0412345678']})
res = product(*a.values())
for line in res:
print " ".join(["%s=%s" % (m, n) for m,n in zip(a.keys(), line) ])
result
s=Party! f=0412345678 flag=urgent id=1221AB12 t=0523456789
s=Party! f=0412345678 flag=urgent id=1221AB12 t=0301234567
s=Party! f=0412345678 flag=english id=1221AB12 t=0523456789
s=Party! f=0412345678 flag=english id=1221AB12 t=0301234567
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With