I have a text file containing coordinates in the form of:
[-1.38795678, 54.90352965]
[-3.2115, 55.95530556]
[0.00315428, 51.50285246]
I want to be able to iterate through each coordinate to check which polygon it is in (UK counties in a shapefile), however I am not sure how to tokenise the numbers so that I can have a code along the lines of...
for line in coordinates:
for poly in polygons:
if points in polygons:
print(polygons)
break
if points not in polygons:
continue
At the moment they are strings but I want to each line to be comprised of the two points so I that the program can try and locate them in a polygon.
You could turn the string into a tuple using literal_eval
.
>>> from ast import literal_eval
>>> s = "[-1.38795678, 54.90352965], [-3.2115, 55.95530556], [0.00315428, 51.50285246]"
>>> seq = literal_eval(s)
>>> print seq[0][1]
54.90352965
Edit: if the coordinates are on separate lines with no commas,
from ast import literal_eval
s = """[-1.38795678, 54.90352965]
[-3.2115, 55.95530556]
[0.00315428, 51.50285246]"""
seq = [literal_eval(line) for line in s.split("\n")]
#or
seq = literal_eval(s.replace("\n", ","))
print seq[0][1]