0

I am trying to extract the positions using regular expressions in a file like this:

 36 17.89 N,  2 51.62 W
 35 51.13 N,  2 51.62 W
 35 51.13 N,  2 49.14 W
 36 17.89 N,  2 49.14 W
 36 17.89 N,  2 46.66 W
 35 51.13 N,  2 46.66 W
 35 51.13 N,  2 44.18 W
 36 17.89 N,  2 44.18 W
 36 17.89 N,  2 41.7 W
 35 51.13 N,  2 41.7 W
 35 51.13 N,  2 39.22 W
 36 17.89 N,  2 39.22 W
 36 17.89 N,  2 36.74 W
 35 51.13 N,  2 36.74 W
 35 51.13 N,  2 34.26 W
 36 17.89 N,  2 34.26 W

It is a .txt file.

The regex for extract the data is :

pattern = r'((?m)^\t\s([1-9]?[0-9])\s([0-9]?[0-9]\.?[0-9]{0,2}))\s([NS]),\s{0,2}([1-9]?[0-9])\s([0-9]?[0-9]\.?[0-9]{0,2}).([WE])'

I can extract the groups to process strings to float but I want to know how can I store in a list the number of the match as a 'ID' of each line

for example (3, 35.8521,-2.685666)

in a list, a tuple or some iterable

1
  • You enumerate() through each line, and append a tuple like you suggest to a list inside that loop?
    – user707650
    Oct 8, 2014 at 15:08

2 Answers 2

0

I would use split instead of regex:

with open('coordinates.txt','r') as file:
    for line in file:
        coord = [pair.split() for pair in line.split(',')]
0

Use enumerate to get the index of each line, like so:

import re
pattern = re.compile(
    r'(?m)^\s*([0-9]+)\s*([0-9.]+)\s*([NS]),\s*([[0-9]+)\s*([0-9.]+)\s*([WE])')
with open('in.txt') as f:
    result = [
        (i, lat, lng) for i, (lat, lng) in enumerate(
            ((int(lat) + float(latf) / 60) * (1 if latdir == 'N' else -1),
             (int(lng) + float(lngf) / 60) * (1 if lngdir == 'E' else -1))
            for lat, latf, latdir, lng, lngf, lngdir
            in pattern.findall(f.read()))]

from pprint import pprint
pprint(result)

Or, if you prefer each step in its own statement:

with open('in.txt') as f:
    # Get the characters from the file
    data = f.read()

# Find the formatted fields
data = pattern.findall(data)

# Convert the string fields into numeric values
data = (((int(lat) + float(latf) / 60) * (1 if latdir == 'N' else -1),
     (int(lng) + float(lngf) / 60) * (1 if lngdir == 'E' else -1))
    for lat, latf, latdir, lng, lngf, lngdir in data)

# Add an index
data = enumerate(data)

# Flatten the tuple
data = ((i, lat, lng) for i, (lat, lng) in data)

# And there you are
result = list(data)

In either case, if you want 1-based indexes, use (i+1, lat, lng) for i, ....

1
  • Great. Simple but accurate
    – kamome
    Oct 8, 2014 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.