2

我有一个文本文件,其中包含以下形式的坐标:

[-1.38795678, 54.90352965]
[-3.2115, 55.95530556] 
[0.00315428, 51.50285246]

我希望能够遍历每个坐标以检查它在哪个多边形中(shapefile 中的英国县),但是我不确定如何标记数字,以便我可以有一个代码...

for line in coordinates:
    for poly in polygons:
        if points in polygons:
            print(polygons)
            break

        if points not in polygons:
            continue

目前它们是字符串,但我希望每条线由两个点组成,以便程序可以尝试将它们定位在多边形中。

4

2 回答 2

3

您可以使用将字符串转换为元组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

编辑:如果坐标在没有逗号的单独行上,

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]
于 2015-12-01T14:13:42.457 回答
1

您还可以使用比 ast 快得多的正则表达式:

import re
with open("in.txt") as f:
    r = re.compile("[-]?\d+\.\d+")
    data = [list(map(float, r.findall(line))) for line in f]

一些时间安排:

In [14]: %%timeit
with open("test.txt") as f:
    data = [literal_eval(line) for line in f]
   ....: 
100 loops, best of 3: 2.01 ms per loop

In [15]: %%timeit
with open("test.txt") as f:
    r = re.compile("[-]\d+\.\d+")
    data = [list(map(float, r.findall(line))) for line in f]
   ....: 
1000 loops, best of 3: 403 µs per loop

 with open("test.txt") as f:
    r = re.compile("[-]?\d+\.\d+")
    data = [list(map(float, r.findall(line))) for line in f]
   ....:     

In [38]: with open("test.txt") as f:
           data2 = [literal_eval(line) for line in f]
   ....:     

In [39]: data == data2
Out[39]: True

只是剥离和拆分会再次更快:

In [40]: %%timeit
   ....: with open("test.txt") as f:
   ....:     data = [list(map(float, line.strip("[]\n").split(","))) for line in f]
   ....: 
1000 loops, best of 3: 249 µs per loop
于 2015-12-01T14:52:33.227 回答