Python - 从文件中的每一行中提取特定数字

时间:2015-05-28 21:05:34

标签: python string

我有一个文本文件,其中包含1000行文本,但我只对大文本文件中的某些行感兴趣,并从这些行中提取一些有趣的数字。以下是示例文本文件 -

[Some text]
[Some text]
......
01/12/14 17:19:01.942 DEBUG [MaccParamsProducts-5] Get location (x,y,z,storeid,bustLeard,confidence): (50.0,41.153217,0.0,215,9,194.0)
......
[Some text]
[Some text]
......
01/18/14 17:29:54.852 DEBUG [MaccParamsProducts-2] Get location (x,y,z,storeid,bustLeard,confidence): (60.0,51.253947,0.0,125,10,194.0)

现在,我有兴趣只获取包含字符串"获取位置"的行。 一旦我得到那条线,我就只想获得x和y坐标值。例如,在上面的获取位置行中,我想只获得60.0和51.253947。我的最终输出应该只有这两个值。

到目前为止,我已经能够获得线条而不是值,因为我对python很新。以下是我的代码段 -

import sys
with open("test.log", "r") as input_file:
     with open('res4.txt', 'w') as output_file:
                output_file.write("Lines containing x-y co-ordinates\n")
                for line in input_file:
                        if "Get location" in line:
                                output_file.write(line)

如果有人能告诉我如何提取这两个值并将其输出到一个新的文本文件中,那就太棒了!任何形式的帮助都表示赞赏。

2 个答案:

答案 0 :(得分:5)

with open("test.txt") as f:
    for line in f:
        if "Get location" in line:
            data = line.rsplit(None,1)[1]
            print(data.strip("()").split(",", 2)[:2])

输出:

['50.0', '41.153217']
['60.0', '51.253947']

要将其写入文件,只需打开另一个文件并随时写入:

import csv
with open("test.txt") as f,open("out.txt","w")as out:
    wr = csv.writer(out)
    for line in f:
        if "Get location" in line:
            data = line.rsplit(None,1)[1]
            wr.writerow(data.strip("()", 2).split(",")[:2])

out.txt:

50.0,41.153217
60.0,51.253947

line.rsplit(None,1)[1]从最后的空白处拆分一次,我们剥离()并拆分,获取前两个数字。

或者使用file.write并解压缩:

with open("test.txt") as f,open("out.txt","w") as out:
    for line in f:
        if "Get location" in line:
            a,b,_ = line.rsplit(None,1)[1].strip("()").split(",", 2)
            out.write("{},{}\n".format(a,b))

答案 1 :(得分:1)

Python是必需品吗?这是Shell工具的完美工作:

grep 'Get location' | sed 's/.*: (\([^,]*\),\([^,]*\),.*/\1, \2/'