I have a .txt file like this:
# 经纬度
x1 = 11.21
x2 = 11.51
y1 = 27.84
y2 = 10.08
time: 201510010000
变量名: val1
[1.1,1.2,1.3]
变量名: va2
[1.0,1.01,1.02]
time: 201510010100
变量名: val1
[2.1,2.2,2.3]
变量名: va2
[2.01,2.02,2.03]
time: 2015020000
变量名: val1
[3.0,3.1,3.2]
变量名: val2
[3.01,3.02,3.03]
time: 2015020100
变量名: val1
[4.0,4.1,4.2]
变量名: val2
[401,4.02,4.03]
and, I hope to read it using python like this:
with open('text.txt','r',encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
print(line,)
This is what I have done, but I have no idea about the next step.
How can I reach it?
I am learning python and this is what I came up with :) Someone who reads the solution and finds mistakes, please be kind to point out.
time = ""
val1 = []
val2 = []
final_list = []
process_val1 = False
process_val2 = False
with open('read.txt','r',encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
try:
line = line.strip()
if val1 and val2 and time != '':
for v1, v2 in zip(val1, val2):
final_list.append([time, v1, v2])
val1 = []
val2 = []
time = ''
continue
if process_val1 == True:
val1 = line.split('[')[1].split(']')[0].split(',')
process_val1 = False
continue
if process_val2 == True:
val2 = line.split('[')[1].split(']')[0].split(',')
process_val2 = False
continue
if 'time:' in line:
time = line.split(": ")[1]
continue
elif 'val1' in line:
process_val1 = True
continue
elif 'val2' in line:
process_val2 = True
continue
elif 'va2' in line:
process_val2 = True
continue
else:
continue
except:
#handle exception here
pass
if final_list:
with open('write.txt', 'w') as w:
for list in final_list:
w.write(", ".join(list) + '\n')