两点截取线【shapely】【clipline】
from shapely.geometry import Point, LineString from shapely.ops import snap, split, nearest_points def clipLine(ls, p1, p2): p1 = nearest_points(ls, p1)[0] geom = snap(ls, p1, 1) parts = split(geom, p1).geoms # 新版本的shapely对该函数的返回值做了改动 if len(parts) == 1: fp = parts[0] else: fp = parts[0] if parts[0].distance(p2) < parts[1].distance(p2) else parts[1] p2 = nearest_points(fp, p2)[0] geom = snap(fp, p2, 0.1) parts = split(geom, p2).geoms # if len(parts) == 1: res = parts[0] else: res = parts[0] if parts[0].distance(p1) < parts[1].distance(p1) else parts[1] return res if __name__ == '__main__': ls = LineString([(0, 0), (5, 5)]) p1 = Point((1, 1)) p2 = Point([3, 3]) res = clipLine(ls, p1, p2) print(res.wkt) # LINESTRING (1 1, 3 3)