在 Python 中使用正则表达式从字符串中提取坐标

Extract coordinates from a string using regex in Python

我有多个字符串如下:

LINESTRING (-3.1 2.42, 5.21 6.1, -1.17 -2.23)
LINESTRING (1.83 9.5, 3.33 2.87)

预期结果是包含元组格式的相应坐标的列表:

[(-3.1,2.42),(5.21,6.1),(-1.17,-2.33)]
[(1.83,9.5),(3.33,2.87)]

请注意,字符串中的坐标数是未知的且可变的。现在,我在删除括号外的字符后使用 split 函数两次。有什么优雅的方法可以使用 Regex.

来精确坐标

以下是使用 for 循环的方法:

import re

strings = ['LINESTRING (-3.1 2.42, 5.21 6.1, -1.17 -2.23)',
           'LINESTRING (1.83 9.5, 3.33 2.87)']

for string in strings:
    st = re.findall('(?<=[(,]).*?(?=[,)])', string)
    print([tuple(s.split()) for s in st])

输出:

[('-3.1', '2.42'), ('5.21', '6.1'), ('-1.17', '-2.23')]
[('1.83', '9.5'), ('3.33', '2.87')]

是否要求使用正则表达式?我发现普通的 ol' 字符串拆分更易于维护:

strings = [
    "LINESTRING (-3.1 2.42, 5.21 6.1, -1.17 -2.23)",
    "LINESTRING (1.83 9.5, 3.33 2.87)",
]

for s in strings:
    # Collect stuff between parentheses
    inside = s.split("(")[1].split(")")[0]

    pairs = []
    for pair in inside.split(", "):
        left, right = pair.split(" ")
        pairs.append((float(left), float(right)))

    print(pairs)

这不是一个非常聪明的解决方案 -- 它是相当蛮力的 -- 但如果它在凌晨 2 点中断,我想我能够弄清楚它到底在做什么。