Python - extracting specific numbers from each line in a file

I have a text file that has 1000 lines of text, but I'm only interested in finding certain lines in a large text file and extracting some interesting numbers from those lines. Following is an example of a text file -

[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)

      

Now I am interested in getting only the lines with the string "Get Location". Once I get this line, I'm only interested in getting the x and y coordinates. For example, in the Get location line above, I only want to get 60.0 and 51.253947. My end result should only have these 2 values.

So far I have managed to get strings but not values ​​as I am very new to python. Following is the code snippet -

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)

      

If anyone can tell me how to extract these 2 values ​​and output them to a new text file, that would be great! Any help is appreciated.

+3


source to share


2 answers


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])

      

Output:

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

      

To write it to a file, just open some more and write as you go:

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]

is split once per space from the end, we separate ()

and divide by ,

to get the first two numbers.

Or use file.write and unpack:

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))

      

+5


source


Is Python a must? This is the perfect job for Shell tools:



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

      

+1


source







All Articles