提取混合日志文件中的关键数字

2024-06-07 06:00:45 发布

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

我有一个日志文件,其中包含许多类似这样的片段:

Align set A and merge into set B ...
    setA, 4 images , image size 146 X 131
    setA, image 1, shape center shift (7, -9) compared to image center
    setA, image 2, shape center shift (8, -10) compared to image center
    setA, image 3, shape center shift (6, -9) compared to image center
    setA, image 4, shape center shift (6, -8) compared to image center
    final set B, image size 143 X 129
Write set B ...

现在,我想把这个片段中的数字提取到一个表中:

| width_A | height_A | shift_x | shift_y | width_B | height_B|
--- | --- | --- | ----| ---
A1 | 146 | 131 | 7 | -9 | 143 | 129
A2 | 146 | 131 | 8 | -10 | 143 | 129
A3 | 146 | 131 | 6 | -9 | 143 | 129
A4 | 146 | 131 | 6 | -8 | 143 | 129

如果将程序分为两部分,则:

  1. 文本处理,将文本读入字典data,例如data['A1']['shift_x'] = 7。你知道吗
  2. 使用pandas将字典转换为dataframe:df = pd.DataFrame(data)

但我不熟悉python文本处理:

有人有解决这个问题的好办法吗?首选Python。提前谢谢。你知道吗


Tags: toimage文本datasizeshifta1width
1条回答
网友
1楼 · 发布于 2024-06-07 06:00:45

我自己终于找到了答案:

import re

# store attribute as a turple, construct a dictionary, turple_attribute: pattern
regexp = {
    ('title', ): re.compile(r'Merge (.*) into set B.*\n' ),
    ('nimages', 'height_A', 'width_A'): re.compile(r'\s+setA, (\d{1,}) images , image size (\d{1,}) X (\d{1,}).*\n'),
    ('image_no', 'shift_x', 'shift_y'): re.compile(r'\s+setA, image (\d{1,}), shape center shift \((-?\d{1,}), (-?\d{1,})\) compared to image center.*\n'),
    ('gauge_no', ): re.compile(r'Write gauge (\d{1,}), set B.*') }

with open(log_file) as f:
    for line in f:
        print(line)
        for keys, pattern in regexp.iteritems():
            m = pattern.match(line)
            if m:          
                # traverse attributes
                for groupn, attr in enumerate(keys):  
                    # m.group(0): content of the entrire line
                    print str(groupn)+' '+attr + ' ' + m.group(groupn+1)

参考

  1. 在我问Extracting info from large structured text files之前没有注意到这个问题
  2. Regular expression cheat table

相关问题 更多 >