我正在制作一个脚本来循环访问多个日志文件,并希望从某些行中提取信息并将其显示为格式化表,以检查所有值,第一列中的行将用作列名和附加的值这些列。
文件_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
答案 0 :(得分:0)
您可能要处理一个正则表达式事务中的所有字符串操作。您可以在捕获组中捕获所需的数据来执行此操作。因此,解决方案可能看起来像这样。
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'}}