# Break a shapely Linestring at multiple points

This code below was modified from the one I found here which splits a shapely Linestring into two segments at a point defined along the line. I have also checked other questions but they don't address my query directly. However I will like to extend it to split the line into multiple segments (at multiple points), all my attempts to do that so far has failed. How can it be modified to split the string into any given number of segments or at multiple points say ((4,5),(9,18) and (6,5)).

``````input:

line = LineString([(1,2),(8,7),(4,5),(2,4),(4,7),(8,5),(9,18),(1,2),(12,7),(4,5),(6,5),(4,9)])
breakPoint = Point(2,4)

from shapely.geometry import Point,LineString

def make_line_segment(line_string, breakPoint):
geoLoc = line_string.coords
j = None
for i in range(len(geoLoc) - 1):
if LineString(geoLoc[i:i + 2]).intersects(breakPoint):
j = i
break
assert j is not None
# Make sure to always include the point in the first group
if Point(geoLoc[j + 1:j + 2]).equals(breakPoint):
return geoLoc[:j + 2], geoLoc[j + 1:]
else:
return geoLoc[:j + 1], geoLoc[j:]

line1,line2 = make_line_segment(line,breakPoint)
line1 = LineString(line1)
line2 = LineString(line2)
print line1, line2

output: `LINESTRING (1 2, 8 7, 4 5, 2 4) LINESTRING (2 4, 4 7, 8 5, 9 18, 1 2, 12 7, 4 5, 6 5, 4 9)`
``````

Shapely has now the split function (see Split lines at points using Shapely) ``````points = MultiPoint([(4,5),(9,18),(6,5)])
line = LineString([(1,2),(8,7),(4,5),(2,4),(4,7),(8,5),(9,18),(1,2),(12,7),(4,5),(6,5),(4,9)])
from shapely.ops import split
splitted = split(line, points)
for lin in splitted:
print lin
LINESTRING (1 2, 8 7, 4 5)
LINESTRING (4 5, 2 4, 4 7, 8 5, 9 18)
LINESTRING (9 18, 1 2, 12 7, 4 5, 6 5)
LINESTRING (6 5, 4 9)
`````` • thanks, @gene, unfortunately, I can't get the from shapely.ops import split to work. I get this error ( import split from shapely.ops import split ImportError: cannot import name split)? how can I import split – Nobi Sep 10 '16 at 12:46
• You can try and just use "import shapely" and access it via "shapely.ops.split()" – Matte Sep 10 '16 at 14:18
• @Matte i get an attribute error: AttributeError: 'module' object has no attribute 'ops' – Nobi Sep 10 '16 at 14:26
• look at obs.py line 330 – gene Sep 10 '16 at 15:41
• Technically, `split()` isn't available until 1.6.0 is released, but we have prereleases on PyPI: pypi.python.org/pypi/Shapely/1.6a1, or `pip install -U pip && pip install --pre shapely==1.6a1`. – sgillies Sep 19 '16 at 11:45