1

I need some support to real a polygon. Today I have a string and I need to change in a format that is possible to recognize as a polygon.

I am acquiring directly from SQL the value of polygon:

Example:

I read on this way:

string = "POLYGON ((-47.158846224312285 -21.349760242365733;-47.158943117468695 -21.349706412900805;-47.159778541623055 -21.349008036758804))"

I need to change in this format

list = [(-47.158846224312285,  -21.349760242365733), (47.158943117468695 -21.349706412900805),  (-47.159778541623055, -21.349008036758804)]

Any idea how to modificate?

  • Where is the class `POLYGON` defined? Are you using a 3rd party module or is it something you have created? If it is the latter please [edit] your question and add the class definition to it. – martineau Jul 22 '16 at 18:27
  • Sorry, in this case POLYGON is no t a class, it is part of an entire string that cames from SQL – Raphael Castilho Gil Jul 22 '16 at 18:32
  • I would rewrite this question to be a little more clear. The example is clear but the introductory paragraph is confusing - specifically the statement "change in a format that is possible to recognize as a polygon." – theorifice Jul 22 '16 at 19:04
  • Related: [Shapely: Polygon from String?](https://stackoverflow.com/questions/51855917/shapely-polygon-from-string) – Georgy Jul 26 '19 at 07:45

2 Answers2

2

You can try parsing the string with a regular expression via the re module something like this:

import re

pat = re.compile(r'''(-*\d+\.\d+ -*\d+\.\d+);*''')
s = "POLYGON ((-47.158846224312285 -21.349760242365733;-47.158943117468695 -21.349706412900805;-47.159778541623055 -21.349008036758804))"

matches = pat.findall(s)
if matches:
    lst = [tuple(map(float, m.split())) for m in matches]
    print(lst)

Output:

[(-47.158846224312285, -21.349760242365733), (-47.158943117468695, -21.349706412900805), (-47.159778541623055, -21.349008036758804)]
martineau
  • 119,623
  • 25
  • 170
  • 301
0

Depending on how string your inputs are, this may be an easy case to simply use some string manipulation regular expression library and some string manipulation.

import re
# create a regular expression to extract polygon coordinates
polygon_re = re.compile(r"^POLYGON \(\((.*)\)\)") 
input = "POLYGON ((-47.1 -21.3;-47.1 -21.3;-47.1 -21.3))"
polygon_match = polygon_re.match(input)

if polygon_match is not None:
    coords_str = polygon_match.groups()[0]

    # parse string of coordinates into a list of float pairs
    point_strs = coord_str.split(";")
    polygon = [[float(s) for s in p.split()] for p in coords_str.split(";")]
theorifice
  • 670
  • 3
  • 9