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

在Python中使用正则表达式从字符串中提取坐标,python,re,Python,Re,我有多个字符串,如下所示: 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有什么优雅的方法精确坐标吗?以下是如

我有多个字符串,如下所示:

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

有什么优雅的方法精确坐标吗?以下是如何使用
进行
循环:

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])

是否要求使用regexp?我发现普通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点出现故障,我想我能够弄清楚它到底在做什么。

希望这个答案能帮助您:
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)