分析可变长度python字符串的成员

2024-04-26 22:52:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python中的sed将日志文件中的文本读入单个字符串。在

命令如下:

sys_output=commands.getoutput('sed -n "/SYS /,/Tot /p" %s.log' % cim_input_prefix)

这是系统输出的打印输出

^{pr2}$

它有三个组,有[2,1,3]行感兴趣。在

我的脚本将遇到的日志文件可能具有可变数量的组和行,因此我不能简单地拆分字符串并提取有用的信息。在

我对组和行的索引以及内存列感兴趣。在

如何解析此大字符串以获取字典,例如:

{'1-1': 92, '1-2': 2, '2-1': 1, '3-1': 8, '3-2': 200, '3-3': 6}?

非常感谢您抽出时间


Tags: 文件字符串文本命令loginputoutputsys
1条回答
网友
1楼 · 发布于 2024-04-26 22:52:54

基于输出的特定特性的某种状态机可能比过多地担心索引更容易。在

这个代码片段与示例一起工作,可以对其进行定制以处理转角情况。在

import collections

with open("cpu_text", "r") as f:
    lines = f.readlines()

lines = [line.strip() for line in lines]

group_id = 0
group_member_id = 0
output_dict = collections.OrderedDict()

for line in lines:
    if line.find("SYS") > -1:
        group_id += 1
    elif line.find("Tot") > -1:
        group_member_id = 0
    else:
        group_member_id += 1
        key = "{0}-{1}".format(group_id, group_member_id)
        memory = line.split()[7]
        output_dict[key] = memory

print(output_dict)

输出:

^{pr2}$

相关问题 更多 >