gpt4 book ai didi

python - 如何简化函数以查明字符串是否包含描述多边形的坐标?

转载 作者:行者123 更新时间:2023-11-28 17:14:26 28 4
gpt4 key购买 nike

我有以下字符串:

points = "34.09352 -118.27483, 34.0914 -118.2758, 34.082 -118.2782, 34.0937 -118.2769, 34.0933 -118.2748"

points 是一个包含以逗号分隔的坐标值(纬度和经度)的字符串。

我想检查这个字符串是否仅包含整数或浮点值,以及第一个坐标是否等于最后一个。

我有以下代码:

def validate_points(points):
coordinates = points.split(',')

for point in coordinates:
latlon = point.split(' ')

latitude = latlon[0]
longitude = latlon[1]
if not is_number(latitude) or not is_number(longitude):
raise WrongRequestDataError("Please, specify the correct type of points value. It must be a numeric value")

first = coordinates[0]
last = coordinates[len(coordinates) - 1]
if first != last:
raise WrongRequestDataError("Incorrect points format, the first point must be equal to last")

def is_number(s):
try:
if float(s) or int(s):
return True
except ValueError:
return False

有什么方法可以简化或加速这段代码吗?

最佳答案

您的输入几乎看起来像 WKT polygon .

使用 shapely根据 Python 的 "Easier to ask for forgiveness than permission",您可以简单地尝试将这些点解析为 WKT,看看会发生什么。原理:

# pip install shapely
from shapely import wkt

def is_well_defined_polygon(points):
try:
wkt.loads("POLYGON((%s))" % points)
return True
except:
return False

points = "34.09352 -118.27483, 34.0914 -118.2758, 34.082 -118.2782, 34.0937 -118.2769, 34.0933 -118.2748, 34.09352 -118.27483"

print(is_well_defined_polygon(points))
# True
print(is_well_defined_polygon("1 2, 3 4"))
# IllegalArgumentException: Points of LinearRing do not form a closed linestring
# False
print(is_well_defined_polygon("a b c d"))
# ParseException: Expected number but encountered word: 'a'
# False

关于python - 如何简化函数以查明字符串是否包含描述多边形的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45193310/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com