对字符串进行标记整数

时间:2015-12-01 14:12:08

标签: python string integer coordinates pysal

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

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

我希望能够遍历每个坐标以检查它所在的多边形(英国各个形状文件中的县),但是我不知道如何标记数字以便我可以拥有一行代码。 ..

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

        if points not in polygons:
            continue

目前它们是字符串,但我希望每一行都包含两个点,所以程序可以尝试在多边形中找到它们。

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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