Skip to content

Instantly share code, notes, and snippets.

@carlosefonseca
Created February 12, 2013 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosefonseca/4771937 to your computer and use it in GitHub Desktop.
Save carlosefonseca/4771937 to your computer and use it in GitHub Desktop.
Takes a KML with multiple LineString's and merges them into one, sequentially.
#!/usr/bin/env python
import codecs
from bs4 import BeautifulSoup
import sys
contents = open(sys.argv[1]).read()
soup = BeautifulSoup(contents, features="xml")
allLineStrings = soup.find_all("LineString")
singleLine = u""
for ls in allLineStrings:
singleLine += " "+" ".join(list(ls.stripped_strings))
for ls in allLineStrings:
ls.parent.decompose()
newTag = BeautifulSoup("<Placemark><name>Percurso</name><LineString><coordinates/></LineString></Placemark>",features="xml")
newTag.find("coordinates").string = singleLine
soup.find("Document").append(newTag.contents[0])
codecs.open(sys.argv[1].replace(".kml","_merged.kml"), mode='w', encoding="utf-8").write(soup.prettify())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment