我正在尝试处理一个看起来或多或少像这样的文件:
f=0412345678 t=0523456789 t=0301234567 s=Party! flag=urgent flag=english id=1221AB12
我知道我可以使用Python shlex解析那些没有重大问题的东西:
entry = "f=0412345678 t=0523456789 t=0301234567 s=Party! flag=urgent flag=english id=1221AB12"
line = shlex.split(entry)
然后我可以执行for循环并迭代键值对。
row = {}
for kvpairs in line:
key, value = kvpairs.split("=")
row.setdefault(key,[]).append(value)
print row
结果:
{'id': ['1221AB12'], 's': ['Party!'], 'flag': ['urgent', 'english'], 't': ['0523456789', '0301234567'], 'f': ['0412345678']}
到目前为止一直很好,但我找不到输出原始行的有效方法,以便输出看起来像:
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
答案 0 :(得分:5)
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) ])
结果
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