Python根据关键字逐行提取文本内容

在获取测试的一些数据时,需要对数据重新提取保存,因此记录。

原始文本样式:

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") # 去掉逗号再加上换行即可
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南洲.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值