Python解析器从输出中提取keyvalue对

时间:2011-10-05 01:32:30

标签: python parsing text

我刚开始使用python,并且从文本输出中提取数据。文本输出采用文本块的形式,并具有键值对

status active
name server01
read:bytes 4096
user abcd-12345-def
drive hgbcv-76s7e-hwte7ehxd-22byt82h
write:bytes 4096
read:requests 1
type disk
write:requests 1
size 1099511627776
status active
name server02
read:bytes 4096
user abcd-12345-def
drive ngcdha6-76eg-78q7dg73-76eydh
write:bytes 4096
read:requests 1
type disk
write:requests 1
size 1099511627776

我需要解析每个块并将输出显示为

status,name,drive,type,disk

所以对于上面的例子,我应该能够将输出作为

active,server01,hgbcv-76s7e-hwte7ehxd-22byt82h,disk,1099511627776
active,server02,ngcdha6-76eg-78q7dg73-76eydh,disk,1099511627776

任何有助于实现这一目标的帮助或指针都将受到高度赞赏。

谢谢

1 个答案:

答案 0 :(得分:0)

这大概就是你想要的:

def create_dict(lines):
    return dict(line.split(" ") for line in lines)

lines1 = [
    "status active",
    "name server01",
    "read:bytes 4096",
    "user abcd-12345-def",
    "drive hgbcv-76s7e-hwte7ehxd-22byt82h",
    "write:bytes 4096",
    "read:requests 1",
    "type disk",
    "write:requests 1",
    "size 1099511627776",
]
lines2 = [
    "status active",
    "name server02",
    "read:bytes 4096",
    "user abcd-12345-def",
    "drive ngcdha6-76eg-78q7dg73-76eydh",
    "write:bytes 4096",
    "read:requests 1",
    "type disk",
    "write:requests 1",
    "size 1099511627776",
]

d1 = create_dict(lines1)
d2 = create_dict(lines2)

keys = ("status","name","drive","type","size")
for d in (d1, d2):
    print ",".join(d[key] for key in keys)

这是我得到的输出:

>>> for d in (d1, d2):
...     print ",".join(d[key] for key in keys)
... 
active,server01,hgbcv-76s7e-hwte7ehxd-22byt82h,disk,1099511627776
active,server02,ngcdha6-76eg-78q7dg73-76eydh,disk,1099511627776

您需要找到一种方法将相关的行放在一起以调用create_dict,然后您可以过滤所需的键。

请注意,您的密钥“磁盘”应为“尺寸”。