python实现一组典型数据格式转换

yipeiwu_com7年前Python基础

本文实例为大家分享了一组典型数据格式转换的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来处理,代码如下:

# 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()

生成文件格式如下,基本上满足了需求。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 给DataFrame增加index行名和columns列名的实现方法

python 给DataFrame增加index行名和columns列名的实现方法

在工作中遇到需要对DataFrame加上列名和行名,不然会报错 开始的数据是这样的 需要的格式是这样的: 其实,需要做的就是添加行名和列名,下面开始操作下。 # a是Data...

详解python while 函数及while和for的区别

详解python while 函数及while和for的区别

1.while循环(只有在条件表达式成立的时候才会进入while循环) while 条件表达式:   pass while 条件表达式:   pass else:   pass 不知道...

详解Django+uwsgi+Nginx上线最佳实战

什么是uwsgi? uWSGI是一个Web服务器,它实现了WSGI协议、uwsgi、http等协议。Nginx中HttpUwsgiModule的作用是与uWSGI服务器进行交换。WSG...

python 实现视频流下载保存MP4的方法

如下所示: # -*- coding:utf-8 -*- import sys import os from glob import glob import requests...

python将字符串转换成数组的方法

python将字符串转换成数组的方法。分享给大家供大家参考。具体实现方法如下: #----------------------------------------- # N...