[英]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
function 兩次。 有沒有什么優雅的方法可以使用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])
Output:
[('-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 點中斷,我想我能夠弄清楚它實際上在做什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.