在获取测试的一些数据时,需要对数据重新提取保存,因此记录。
原始文本样式:
2018-09-06 16:42 - INFO - Coordinate: [-285.444793701, 1958.66479492, 175.649078369], End of execution.
2018-09-06 16:43 - INFO - Coordinate: [-301.866485596, 1959.87561035, 175.649200439], End of execution.
2018-09-06 16:44 - INFO - Coordinate: [-318.365051275, 1960.27978516, 175.646804815], End of execution.
2018-09-06 16:45 - INFO - Coordinate: [-334.736816406, 1961.48742676, 176.991455078], End of execution.
2018-09-06 16:46 - INFO - Coordinate: [-356.053833008, 1962.49230957, 176.991180429], End of execution.
2018-09-06 16:47 - INFO - Coordinate: [-370.848907471, 1962.69274902, 176.989471436], End of execution.
2018-09-06 16:48 - INFO - Coordinate: [-388.050415039, 1963.19372559, 178.462493896], End of execution.
提取代码如下:
# key words to extract the coordinate
str_start = "["
str_end = "]"
f_orig = open('/home/yasin/test_coordinate.txt') # original file
f_coord = open('coordinate_save.txt', 'w') # target file used to save
line = f_orig.readline()
while line:
# find index according to the key words
index_start = line.find(str_start)
index_end = line.find(str_end)
text = line[index_start : index_end]
if text != '':
# If there is more than one [], we can use "Coordinate" and "End" as str_start and str_end
f_coord.write(str(line[index_start + 1 : index_end]) + '\n')
line = f_orig.readline()
f_orig.close()
f_coord.close()
提取后保存样式:
-285.444793701, 1958.66479492, 175.64907836
-301.866485596, 1959.87561035, 175.64920043
-318.365051275, 1960.27978516, 175.64680481
-334.736816406, 1961.48742676, 176.99145507
-356.053833008, 1962.49230957, 176.99118042
-370.848907471, 1962.69274902, 176.98947143
-388.050415039, 1963.19372559, 178.46249389
有的同学问如下问题:
根据vertex关键字在其后面进行换行?
我的方法是对文本按关键字分割并重写文件,如果各位有更好的方法,可以一起探讨!
f_in = open('test.txt') #源文件
f_out = open('out.txt', 'w') #重写文件
line = f_in.readlines() #整个文件读入
key_word = "hello"
line_split = line[0].split(key_word) #按指定单词分割
for i in range(len(line_split)):
if len(line_split[i])>0:
f_out.write(key_word+":"+line_split[i].strip(",")+"\n") # 去掉逗号再加上换行即可