简体   繁体   English

从字符串中提取坐标列表

[英]Extracting List of coordinates from string

Hello Iv been at this all day but have ran into a problem. 你好,我整天都在这里,但是遇到了问题。

I am reading in GeoJson file and trying to extract the coordinates so that I can later iterate throughout them to determine the size of my window to redraw the polygons, represented by a list of coordinates. 我正在阅读GeoJson文件,并尝试提取坐标,以便以后可以遍历它们,以确定窗口的大小以重绘以坐标列表表示的多边形。 Each polygon may have 4 - x coordinate pairs. 每个多边形可以具有4-x个坐标对。 When I read in the GeoJson I get a list containing only 1 element for each polygon instead of a list with a list of coordinates. 当我阅读GeoJson时,我得到一个每个多边形仅包含1个元素的列表,而不是包含坐标列表的列表。 I believe this is because the list reads: [[[-76.2671328, 38.4506304], [-76.2669856, 38.4505256], [-76.2668385, 38.4503701], [-76.2667281, 38.4502182], [-76.2664568, 38.4499759], [-76.2661993, 38.4497843], [-76.2660108, 38.4497192]...]] and there are multiple sets of [[]] which make the list think there is one element inside..? 我认为这是因为该列表显示为: [[[-76.2671328, 38.4506304], [-76.2669856, 38.4505256], [-76.2668385, 38.4503701], [-76.2667281, 38.4502182], [-76.2664568, 38.4499759], [-76.2661993, 38.4497843], [-76.2660108, 38.4497192]...]]和[[]]的多组设置使列表认为其中存在一个元素。

So then i tried converting the list of coordinate to a string so I could remove the extra [[]] and extract the coordinate pairs and turn them back into a list. 因此,然后我尝试将坐标列表转换为字符串,以便删除多余的[[]]并提取坐标对并将它们重新转换为列表。 Here is the code: 这是代码:

import json
import re

with open('landareas.json') as f:
    landareas = json.load(f)

coordinates = []
polygons = []
for feature in landareas['features']:
    polygons.append(feature['geometry']['coordinates'])

print len(polygons)
for polygon in polygons:
    #print type(polygon)
    #print len(polygon)
    string =  str(polygon)  
    newCords = string[2:len(string)-1]
    print newCords
    coordinates.append(re.findall('[(.+?)]', newCords))

for coordinate in coordinates:
    print coordinate
    print   

So now when i do this all i get back is: 所以现在当我这样做时,我得到的是:

['.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.']

With all the numbers stripped out.. :(! 除去所有数字.. :(!

If someone could please help me out in a method to exact the coordinates into a list of coordinates for each polygon so that I can loop through a list of polygons with each containing a list of their coordinates, that would be greatly apprcieated! 如果有人可以帮我一个方法,将坐标精确到每个多边形的坐标列表中,以便我可以遍历一个多边形列表,每个多边形都包含其坐标列表,那将非常感谢!

My initial error which started this was: 我的最初错误是从此开始的:

File "polygon_LatLong_xy.py", line 33, in <module>
    for x,y in polygons[CORDINATES]:
TypeError: 'int' object is not utterable

from this python script: 从这个python脚本:

import turtle as t
import json

RCID = 0
CORDINATES= 1

with open('landareas.json') as f:
    landareas = json.load(f)

polygons = []
for feature in landareas['features']:
    polygons.append([feature['properties']['RCID'], feature['geometry']['coordinates'] ])

map_width = 400
map_height = 400

minx = 180
maxx = -180
miny = 90
maxy = -90

for x,y in polygons[CORDINATES]:
    if x < minx: minx = x
    elif x > maxx: maxx = x
    if y < miny: miny = y
    elif y > maxy: maxy = y

dist_x = maxx - minx
dist_y = maxy - miny

x_ratio = map_width / dist_x
y_ratio = map_height / dist_y

def convert(point):
    lon = point[0]
    lat = point[1]
    x = map_width - ((maxx - lon) * x_ratio)
    y = map_height - ((maxy - lat) * y_ratio)
    #Python turtle graphics start in the middle of the screen 
    #so we must offset the points so the are centered
    x = x - (map_width/2)
    y = y -(map_height/2)
    return [x,y]

t.up()
first_pixel = None
for point in polygons[CORDINATES]:
    pixel = convert(point)
    if not first_pixel:
        first_pixel = pixel
    t.goto(pixel)
    t.down()
t.goto(first_pixel)
t.write(str(polygons[RCID]), align="center", font=("Arial",16,"bold"))
t.up()
t.done()

If its any help here is an excerpt from the geoJson file: 如果有帮助,请参见geoJson文件的摘录:

{
  "type": "FeatureCollection", 
  "features": [
    {
      "geometry": {
        "type": "Polygon", 
        "coordinates": [ <--- note the 
          [ <----------------two sets of brackets? could this be why?              
            [
              -76.0220181, 
              38.1321203
            ], 
            [
              -76.0219133, 
              38.1321847
            ], 
            [
              -76.0232178, 
              38.1312463
            ], 
            [
              -76.0230198, 
              38.1312923
            ], 
            [
              -76.0220181, 
              38.1321203
            ]
          ]
        ]
      }, 
      "type": "Feature", 
      "properties": {
        "TXTDSC": "                                                                                ", 
        "RCID": 3918, 
        "PRIM": 3, 
        "NINFOM": "                                                                                ", 
        "SORIND": "                                                                                ", 
        "RECDAT": "                                                                                ", 
        "AGEN": 550, 
        "GRUP": 1, 
        "SORDAT": "                                                                                ", 
        "OBJL": 71, 
        "NOBJNM": "                                                                                ", 
        "INFORM": "                                                                                ", 
        "LNAM": "0226088C104B1046", 
        "STATUS": "                                                                                ", 
        "RECIND": "                                                                                ", 
        "SCAMAX": null, 
        "NTXTDS": "                                                                                ", 
        "CONDTN": null, 
        "FIDS": 4166, 
        "SCAMIN": null, 
        "FIDN": 143396939, 
        "RVER": 1, 
        "OBJNAM": "                                                                                "
      }
    }, 

I'm not complete sure about your code, but I think your problem is that when you get the string value of the coordinates (in the polygons.append(feature['geometry']['coordinates']) and coordinates.append(re.findall('[(.+?)]', newCords)) , you don't convert them into a list first. 我不确定您的代码,但是我认为您的问题是,当您获取坐标的字符串值(在polygons.append(feature['geometry']['coordinates'])coordinates.append(re.findall('[(.+?)]', newCords)) ,您无需先将它们转换为列表。

Let's say we have a string c = "1, 2" You can do biglist.append(c.split(",")) 假设我们有一个字符串c = "1, 2"您可以执行biglist.append(c.split(","))

One more thing that might help is that you make a set of coordinates for each polygon. 可能有帮助的另一件事是,您为每个多边形创建一组坐标。

#Make a condition that tells the program when to search for the next polygon
polygons = []
polygon = []
for x in landareas['features']:
    if polygonDone:
        polygons.append(polygon)
        del polygon[:]
    else:
        polygon.append(x['geometry']['coordinates'].split(","))

After reading more about re i was able to come up with this bit of code that found the x,y pairs and turn them back into a list of x,y pairs, though they are still represented as a string. 在阅读了有关re的更多信息后,我得以提出了这段代码,找到了x,y对,并将它们重新转换为x,y对列表,尽管它们仍然表示为字符串。

for feature in landareas['features']:
    string_listof_cords = str(feature['geometry']['coordinates'])
    #print string_cords
    string_listof_cords = string_listof_cords.replace(",", "")
    print(re.findall(r'\D\d*\.\d*\s\d*\.\d*', string_listof_cords))

However, in my searching I found a better way to do what I was initially trying todo, manipulate polygons from shape files, and have such aborted this method all together. 但是,在搜索中,我找到了一种更好的方法来做我最初尝试做的事情,操作形状文件中的多边形,并一起放弃了这种方法。 Thanks for the help @ytpillai 感谢您的帮助@ytpillai

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM