如何将.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/21t09:16:56ttest 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/21t11:20:38ttest 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

相关内容

  • 没有找到相关文章

最新更新