gpt4 book ai didi

Python:从标准输出中提取模式并保存在csv中

转载 作者:行者123 更新时间:2023-11-30 22:50:26 26 4
gpt4 key购买 nike

我有大约 20000-30000 行长的日志文件,它们包含各种数据,每行以当前时间戳开始,后跟文件/linu 数字的路径,然后添加一些附加信息(不必要的信息) )。

2016/08/31 17:27:43/usr/log/data/old/objec: 540: Adjustment Stat
2016/08/31 17:27:43/usr/log/data/old/objec: 570: Position: 1
2016/08/31 17:27:43/usr/log/data/old/object::1150: Adding new object in department xxxx
2016/08/31 17:27:43/usr/log/data/old/file1.java:: 728: object ID: 0
2016/08/31 17:27:43/usr/log/data/old/file2.java:: 729: Start location:1
2016/08/31 17:27:43/usr/log/data/old/file1.java:: 730: End location:55
2016/08/31 17:27:43/usr/log/data/old/: 728: object ID: 1
2016/08/31 17:27:43/usr/log/data/old/: 729: Start location:56
2016/08/31 17:27:43/usr/log/data/old/: 730: End location:67
2016/08/31 17:27:43/usr/log/data/old/: 728: object ID: 2
2016/08/31 17:27:43/usr/log/data/old/: 729: Start location:68
2016/08/31 17:27:43/usr/log/data/old/: 730: End location:110
Timer to Calculate location of object x took 0.004935 seconds

.... ... ... 相同的信息......对于新对象每个文件有 30-40 个对象组,它们各不相同(ID 0-3 之间)

I want to extract information (next line after Adjustment Stat)and save in a text file like
Position ObjectID StartLocation EndLocation
0 1 55
1 56 67
2 68 110

... ... ...

(此处没有任何 ID 为 0 的对象) 1 1 50 2 51 109 ...

Or may be store in csv file like
0,1,55
1,56,67
2,68,110

最佳答案

import csv

with open('out.csv', 'w') as output_file, open('in.txt') as input_file:
writer = csv.writer(output_file)
for l in input_file:
if 'object ID:' in l:
object_id = l.split(':')[-1].strip()
elif 'Start location:' in l:
start_loc = l.split(':')[-1].strip()
elif 'End location:' in l:
end_loc = l.split(':')[-1].strip()
writer.writerow((object_id, start_loc, end_loc))

<小时/>2.6版本:

import csv
import contextlib

with contextlib.nested(open('out.csv', 'w'), open('in.txt')) as (output_file, input_file):
writer = csv.writer(output_file)
for l in input_file:
if 'object ID:' in l:
object_id = l.split(':')[-1].strip()
elif 'Start location:' in l:
start_loc = l.split(':')[-1].strip()
elif 'End location:' in l:
end_loc = l.split(':')[-1].strip()
writer.writerow((object_id, start_loc, end_loc))

out.csv(in.txt 如OP中所示)

0,1,55
1,56,67
2,68,110

关于Python:从标准输出中提取模式并保存在csv中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39361621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com