如何将 .log 文件转换为 .csv 文件

汤姆·索亚

我需要帮助将日志文件转换为 .csv 文件。到目前为止,我已经尝试了以下代码,但无法得到我想要的结果。在输入文件中直到“测试控制”,它以“\t”分隔

with open('input.log', 'r') as infile, open('output.csv', 'w') as outfile:
    stripped_lines = (line.strip() for line in infile)
    lines = (line.split(':') for line in stripped_lines if line)
    writer = csv.writer(outfile)
    writer.writerows(lines)

输入文件:

12/15/21    09:16:56    test control: left: 23.2 right: 54.7 test input:85.3 distance:49.5 XY1:15.0 XY2:22.8 ZX1:25.0 ZX2:28.8 MN1:18.7 MN2:18.8 PN1:26.0 PN2:84.5 test speed: 23.2
04/30/21    11:20:38    test control: left: 36.2 right: 88.7 test input:87.4 distance:26.8 XY1:53.0 XY2:85.9 ZX1:95.0 ZX2:78.8 MN1:32.7 MN2:96.8 PN1:52.0 PN2:79.5 test speed: 23.2

输出:

12/15/21,09:16:56,23.2,54.7,85.3,49.5,15.0,22.8,25.0,28.8,18.7,18.8,26.0,84.5,23.2
04/30/21,11:20:38,36.2,88.7,87.4,26.8,53.0,85.9,95.0,78.8,32.7,96.8,52.0,79.5,23.2
乔恩斯格

我对基本答案的第一个猜测是使用该re模块在":"上拆分" "然后我可能只是手动挑选我需要的数据点。

import re
import csv

data_in = '''
12/15/21\t09:16:56\ttest control: left: 23.2 right: 54.7 test input:85.3 distance:49.5 XY1:15.0 XY2:22.8 ZX1:25.0 ZX2:28.8 MN1:18.7 MN2:18.8 PN1:26.0 PN2:84.5 test speed: 23.2
04/30/21\t11:20:38\ttest control: left: 36.2 right: 88.7 test input:87.4 distance:26.8 XY1:53.0 XY2:85.9 ZX1:95.0 ZX2:78.8 MN1:32.7 MN2:96.8 PN1:52.0 PN2:79.5 test speed: 23.2
'''

def parseRow(row):
    el = row.split("\t")
    sub_el = [item for item in re.split(":| ", el[2]) if item]
    return [
        el[0],
        el[1],
        float(sub_el[3]),
        float(sub_el[5]),
        float(sub_el[8]),
        float(sub_el[10]),
        float(sub_el[12]),
        float(sub_el[14]),
        float(sub_el[16]),
        float(sub_el[18]),
        float(sub_el[20]),
        float(sub_el[22]),
        float(sub_el[24]),
        float(sub_el[26]),
        float(sub_el[29]),
    ]

with open('output.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
    writer.writerows(parseRow(row) for row in data_in.split("\n") if row)

根据我解释的数据,这将生成一个如下所示的文件:

12/15/21,09:16:56,23.2,54.7,85.3,49.5,15.0,22.8,25.0,28.8,18.7,18.8,26.0,84.5,23.2
04/30/21,11:20:38,36.2,88.7,87.4,26.8,53.0,85.9,95.0,78.8,32.7,96.8,52.0,79.5,23.2

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章