本文实例为大家分享了一组典型数据格式转换的python实现代码,供大家参考,具体内容如下
有一组源数据,第一行会是个日期数据,第二行标明字段,再接下来是两行数据行。
1018 14:31:30.193
type succ fail
sour_sm 1308 1205
data_sm 2205 3301
1019 16:32:30.201
type succ fail
data_sm 3308 2206
data_sm 1765 1105
1020 18:00:00.203
type succ fail
sour_sm 7804 1105
data_sm 2976 1300
要转换成数据
time type succ fail total
1018 14:31:30.193 sour_sm 1308 1205 2513
1018 14:31:30.193 data_sm 2205 3301 5506
1019 16:32:30.201 data_sm 3308 2206 5514
1019 16:32:30.201 data_sm 1765 1105 2870
1020 18:00:00.203 sour_sm 7804 1105 8909
1020 18:00:00.203 data_sm 2976 1300 4276
这个时候可以使用python来处理,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# coding = utf-8
fd = open (r "output.txt" , "w" , encoding = "utf-8" )
fd.write( "%s\t\t\t\t%s\t%s\t%s\t%s\n" % ( "time" , "type" , "succ" , "fail" , "total" ))
with open (r "data.txt" , "r" , encoding = "utf-8" ) as fd1:
lines = fd1.readlines()
time1 = lines[ 0 :: 4 ]
data1 = lines[ 2 :: 4 ]
data2 = lines[ 3 :: 4 ]
for (i, line) in enumerate (time1):
time = line.strip()
type_1 = data1[i].strip().split()[ 0 ]
succ_1 = data1[i].strip().split()[ 1 ]
fail_1 = data1[i].strip().split()[ 2 ]
total_1 = str ( int (succ_1) + int (fail_1))
type_2 = data2[i].strip().split()[ 0 ]
succ_2 = data2[i].strip().split()[ 1 ]
fail_2 = data2[i].strip().split()[ 2 ]
total_2 = str ( int (succ_2) + int (fail_2))
fd.write( "%s\t%s\t%s\t%s\t%s\n" % (time, type_1, succ_1, fail_1, total_1))
fd.write( "%s\t%s\t%s\t%s\t%s\n" % (time, type_2, succ_2, fail_2, total_2))
fd.close()
|
生成文件格式如下,基本上满足了需求。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Jerry_1126/article/details/84930210