【问题标题】:Extract coordinates from a string using regex in Python在 Python 中使用正则表达式从字符串中提取坐标
【发布时间】:2020-12-19 03:24:43
【问题描述】:

我有多个字符串如下:

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 精确定位坐标。

【问题讨论】:

标签: python re


【解决方案1】:

以下是使用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')]

【讨论】:

    【解决方案2】:

    是否需要使用正则表达式?我发现普通的 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 点中断,我想我就能弄清楚它实际上在做什么。

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      相关资源
      最近更新 更多