【问题标题】:Convert csv- or Excel-file (xlsx) to kml with custom markers使用自定义标记将 csv 或 Excel 文件 (xlsx) 转换为 kml
【发布时间】:2014-11-12 22:17:18
【问题描述】:

我想将 csv 或 Excel(2010) 文件转换为 kml,以便能够在谷歌地球上显示它。 该文件包含未进行地理编码的地址。 它包含一个带有用于自定义标记的 url 的字段。 它包含一个包含一些我想在信息窗口中显示的信息的字段。

文件如下所示:

Name;Category;Address; Icon; Info
McFood;Fast Food;Street 1, zip, town, country; url-to-icon; Info
BurgerEmperor;Fast Food;Way 1, zip, town, country; url-to-icon; Info
BlueFrenchHorn;French;Street 12, zip, town, country; url-to-icon; Info
PetesPizza;Italian;whatever, zip, town, country; url-to-icon; Info
SubZero;Fast Food;Highway 6, zip, town, country; url-to-icon; Info

【问题讨论】:

  • 谁对此投了反对票 - 如果您能解释原因,那就太好了。问题的意图 - 以及给定的答案是为我遇到的问题提供一个解决方案,该解决方案可能对整个 internetz 中的某个人有用。

标签: python excel csv kml google-earth


【解决方案1】:

在社区的帮助下,我想分享我对这个问题的解决方案。 边缘可能有点粗糙,但它有效。我写了两个脚本(一个用于 csv-input,一个用于 xlsx-input,它们只是略有不同)。

CSV 到 KML:

import csv
import simplekml
import geocoder
from collections import defaultdict

mydict = defaultdict(list)

# the part of reading the file to a dictionary is taken from
# http://www.mysamplecode.com/2013/05/python-read-csv-file-list-dictionary.html
# and modified to have a list of dictionaries - solution from
# https://stackoverflow.com/questions/25891451/create-a-list-of-dictionaries-in-a-dictionary-from-csv-in-python/

with open ('food.csv', 'r') as csvfile:
    #sniff to find the format
    fileDialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    #read the CSV file into a dictionary
    dictReader = csv.DictReader(csvfile, dialect=fileDialect)
    for row in dictReader:
        mycategory = row.pop("category")
        mydict[mycategory].append(row)  # Will put a list for not-existing key

mydict = dict(mydict) # Convert back to a normal dictionary (optional)

# Use SimpleKml to write kml-file
# category from csv-file used as folder
# Custom Markers taken from url in csv-file

kml =simplekml.Kml()
for ctgy in mydict:
    fol=kml.newfolder(name=ctgy)
    for entry in mydict[ctgy]:
        # geocode addresses
        g = geocoder.google(entry["Address"])
        pnt=fol.newpoint(name=entry["Name"], coords=[(g.lng,g.lat)], description=entry["Info"])
        if entry["Icon"] != "":
            pnt.style.iconstyle.icon.href=entry["Icon"]
kml.save("food.kml")

XLSX 到 KML:

它只是略有不同 - 为了能够将 DictReader 与 excel 文件一起使用,我使用 xlsdictreader.py 从这个问题的答案: DictReader for Excel-Files

区别在于:

# import csv
from xlsdictreader import XLSDictReader

在文件处理方面:

with open ('food.xlsx', 'r') as excelfile:
    dictReader = XLSDictReader(excelfile)

请发表评论

随意使用脚本。 请评论如何改进它,因为我对 python 比较陌生。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 2023-01-19
    • 2018-07-22
    相关资源
    最近更新 更多