-
-
Save johnson86tw/78691342b1227fa15b09892819734122 to your computer and use it in GitHub Desktop.
This is a modified version of "https://gist.github.com/mciantyre/32ff2c2d5cd9515c1ee7". I modified it to add functionality to save the Name and description of the placemarks in the KML file along with the coordinates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bs4 import BeautifulSoup | |
import csv | |
def main(): | |
""" | |
Open the KML. Read the KML. Make 3 lists for Name, Coordinates and Description of the placemarks. Save the data to a CSV | |
""" | |
name_counter = 0 | |
names_list = [] | |
coords_counter = 0 | |
coords_list = [] | |
desc_counter = 0 | |
desc_list = [] | |
with open('input_file.kml', 'r') as f: | |
s = BeautifulSoup(f, 'xml') | |
for names in s.find_all('name'): #google earth nomenclature. Should read the KML file to see the relevant names we require | |
names_list.append(names.string) | |
names_list = names_list[2:] #only keep names of placemarks | |
name_counter = len(names_list) | |
for coords in s.find_all('coordinates'): | |
coords_list.append(coords.string) | |
coords_list = [string.replace(',9','') for string in coords_list] #here i am manually removing the altitude from coords. Not the best way | |
coords_counter = len(coords_list) | |
for descriptions in s.find_all('description'): | |
desc_list.append(descriptions.string) | |
desc_counter = len(desc_list) | |
print(f'name counter = {name_counter}') #just for testing, all counters should be equal | |
print(f'coords counter = {coords_counter}') | |
print(f'descriptions counter = {desc_counter}') | |
with open('output2.csv', 'w') as file: | |
csv_writer = csv.writer(file) | |
csv_writer.writerow(['Name', 'Coordinates', 'Description']) | |
for counter in range(0, name_counter): | |
csv_writer.writerow( | |
[names_list[counter], coords_list[counter], desc_list[counter]]) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment