用Python對一組典型資料進行格式轉換

2021-09-02 22:12:27 字數 1857 閱讀 9316

有一組源資料,第一行會是個日期資料,第二行標明字段,再接下來是兩行資料行。

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實現一組典型資料格式轉換

有一組源資料,第一行會是個日期資料,第二行標明字段,再接下來是兩行資料行。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 330...

對一組資料進行排序

如果有這種可能的話,三路快排是最好的選擇。是否大部分資料距離它的正確的位置很近?是否近乎有序?如果這樣,插入排序是很好的選擇。是否資料取值的範圍非常有限?比如對學生的成績排序。如果這樣,計數排序是很好的選擇 對排序有什麼額外的要求?是否需要穩定的排序?如果是的話,歸併排序是更好的選擇,快排就不行了。...

selenium python (六)定位一組物件

checkbox原始碼 usr bin python coding utf 8 author zuoanvip 定位單個物件是用find element by id 定位一組物件為find elements by id 其他幾種定位方式都如此 定位一組物件一般用於以下場景 批量操作物件,比如將頁面上...