User9902911
User9902911

Reputation: 91

Python - extracting particular numbers from each line in a file

I have a text file which has 1000's of lines of text but I'm interested in only find certain lines in the big text file and extracting some interesting numbers from those lines. Below is the sample 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'm interested in fetching only the lines that has the string "Get location". Once I get that line, I'm interested in getting only the x and y co-ordinate values. For example in the Get location line above I want to get only 60.0 and 51.253947. My final output should just have those 2 values.

So far, I have been able to get the lines but not the values since I'm very new to python. Below is my 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 somebody could tell me how to extract those 2 values and output it into a new text file, that would be great! Any sort of help is appreciated.

Upvotes: 3

Views: 104

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180522

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 another 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] splits once on whitespace from the end, we strip the () and split on , getting 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))

Upvotes: 5

Michael Lorton
Michael Lorton

Reputation: 44436

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

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

Upvotes: 1

Related Questions