【问题标题】:How to iterate through rows from multiple text files and extract values in a table.如何遍历来自多个文本文件的行并提取表中的值。
【发布时间】:2018-12-24 16:42:16
【问题描述】:

我正在编写一个脚本来遍历多个日志文件,并希望从某些行中提取信息并将其显示为格式化表,以检查所有值、第一列中的行用作列名和附加值到这些列。

文件_1:

   TRACE HEADER=========================================
                    min max
   col_1 [001-004]: 42  55
   col_2 [001-005]: 34  58
   col_3 [001-006]: 94  51
   col_4 [001-007]: 43  27
   col_5 [001-008]: 14  95
   -------------------------------------

文件_2:

   TRACE HEADER=========================================
                    min max
   col_1 [001-004]: 43  55
   col_2 [001-005]: 39  58
   col_3 [001-006]: 91  51
   col_4 [001-007]: 48  25
   col_5 [001-008]: 14  96
   -------------------------------------

我已经尝试遍历行以将文本文件的第一列提取为列标题,并将其他值提取为列表。

import re 
file = "f.txt"


TRC_BEGIN = "TRACE HEADER==="
TRC_END = "---------------"

col_names = []

istrace = False
traceLineCount = 0

log = open(file, "r")

for line in log:

    if line.startswith(TRC_BEGIN):
        istrace = True
    if istrace:
       traceLineCount = traceLineCount + 1
    if istrace and traceLineCount > 2:
       col = re.split("\[\d\d\d\-\d\d\d\]:\s", line)
       #print(col)
       col_1= col[0].strip()
       col_names.append(col_1)
   if line.startswith(TRC_END):
       istrace = False

del col_names[-2:]

预期输出:

         col_1    col_2    col_3    col_4    col_5
file_1   42-55    34-58    94-51    43-27    14-95
file_2   43-55    39-58    91-51    48-25    14-96

【问题讨论】:

  • 您可以像这样使用awk 格式化文件以便于使用 --> cat foo.txt | grep col_* | awk -F " " '{ print $1, $3, "-", $4 }'

标签: python python-3.x


【解决方案1】:

您可能希望在单个正则表达式事务中处理所有字符串操作。您可以通过在捕获组中捕获所需数据来执行此操作。所以一个解决方案可能看起来像这样。

import re
from pathlib import Path


p = re.compile(r'(col_\d+).*?:.(\d+).*?(\d+).*')
results = {}
files = ['test.txt', 'test2.txt']
for file in files:
    if not Path(file).exists():
        continue
    d = {}
    with open(file) as f:
        for line in f:
            m = p.search(line)
            if m:
                d[m.group(1)] = f'{m.group(2)}-{m.group(3)}'
    results[file] = d


print(results) #{'test.txt': {'col_1': '42-55', 'col_2': '34-58', 'col_3': '94-51', 'col_4': '43-27', 'col_5': '14-95'}}

【讨论】:

    猜你喜欢
    • 2014-04-10
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多