【问题标题】:Building a KML in Python用 Python 构建 KML
【发布时间】:2013-05-25 20:45:58
【问题描述】:

我正在尝试从 csv 构建一个 KML 文件以在 Google 地球中显示点,但我遇到了一些小问题... 首先,我可以用它来构建文件,但是 csv 中有六组坐标,而 kml 只显示两个(实际上是一个显示两次)。我显然弄错了循环,但不知道怎么做。 其次,生成的地标 ['53.66018'],['-1.94925'] 显示在某处的海洋中,而它应该在曼彻斯特(英国) 我将不胜感激任何和所有的帮助。提前致谢! 这是 Python 代码-

import csv
import os
fp = "C:\\Python27\\test.csv"
file = open(fp)
lines =file.readlines()
for line in lines:
    line = line.strip()
    fields = line.split(';') #semicolon seperated
    LCID = fields[0].split() #splitting
    CID = fields[1].split()
    LAC = fields[2].split()
    NET = fields[3].split()
    LAT = fields[4].split()
    LON = fields[5].split()

    print 'LCID' #print splitted
    print ("CID: " + str(CID))
   # print ("LAC: " + str(LAC))
   # print ("NET: " + str(NET))
   # print ("LAT: " + str(LAT))
   # print ("LON: " + str(LON))

f = open('C:\\Python27\\csv17kml.kml', 'w')
fname = "testing_Actions"
#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://www.opengis.net/kml/2.2'>\n")
f.write("<Folder>\n")
f.write("   <name> Op Example </name>\n")
for row in lines:
    f.write("   <Placemark>\n")
    f.write("       <ExtendedData>\n")
    f.write("           <Data name='CID'>\n")
    f.write("               <value>\n")
    f.write("               " + str(CID) +"\n")
    f.write("               </value>\n")
    f.write("           </Data>\n")
    f.write("           <Data name='LAC'>\n")
    f.write("               <value>\n")
    f.write("               " + str(LAC) + "\n")
    f.write("               </value>\n")
    f.write("           </Data>\n")
    f.write("       </ExtendedData>\n")
    f.write("       <Point>\n")
    f.write("           <coordinates>" + str(LAT) + "," + str(LON) + "</coordinates>\n")
    f.write("       </Point>\n")
    f.write("   </Placemark>\n")
f.write("</Folder>\n")
f.write("</kml>\n")
print ("File Created. ")
f.close
file.close()

这是 csv 中的数据:

LCID;CID;LAC;NET;LAT;LON

26599;26599;3569;23410;53.66018;-1.94925;
26599;26599;3569;23410;53.66018;-1.94923;
26599;26599;3569;23410;53.66019;-1.94922;
26599;26599;3569;23410;53.66019;-1.94919;
26599;26599;3569;23410;53.66018;-1.94919;
26599;26599;3569;23410;53.66018;-1.94917

这是我添加的页眉和页脚部分...

def write_header(output_file):
    return
"""<?xml version='1.0' encoding='UTF-8'?>\n
<kml xmlns='http://www.opengis.net/kml/2.2'>\n
    <Folder>\n
    <name> Op Example </name>\n"""   

def write_footer(output_file):
    return
"""</Folder>\n")
        </kml>\n
print ("File Created. ")
f.close
file.close()"""

【问题讨论】:

    标签: python loops csv kml


    【解决方案1】:

    除了 Blutack 指出的错误之外,您还阅读了输入文件,但没有将坐标存储在任何地方。

    如果您将代码拆分为更模块化的函数,则更容易推理功能并检查它们是否正常工作。

    另外,您手动执行所有操作也太辛苦了。有一个用于读取csv files 的模块,上下文管理器已经废弃了手动处理文件的关闭,如果你想要多行字符串,你可以使用三引号。此外,如果您想在模板中填写一些值,您可以使用 string formatting 和命名替换以使其更具可读性。

    这就是我想出的:(使用namedtuple 来更舒适地表示每一行)

    from collections import namedtuple
    import csv
    
    location_info = namedtuple('location_info', 'LCID,CID,LAC,NET,LAT,LON')
    input_filename = "input.csv"
    
    def write_header(output_file):
        pass  # left as an excercise
    
    def write_footer(output_file):
        pass  # also left as an exercise
    
    def get_kml(location_info):
        return """    <Placemark>
            <ExtendedData>
                <Data name='CID'>
                    <value>
                        {CID}
                    </value>
                </Data>
                <Data name='LAC'>
                    <value>
                        {LAC}
                    </value>
                </Data>
            </ExtendedData>
            <Point>
                <coordinates>{LON},{LAT}</coordinates>
            </Point>
        </Placemark>""".format(**location_info._asdict())
    
    with open(input_filename, 'r') as input_file:
        csv_reader = csv.reader(input_file, delimiter=';')
        print next(csv_reader)  # gets rid of the header line
        all_locations = (location_info(*line[0:6]) for line in csv_reader)  # the slicing is due to the trailing ;
    
        with open(output_filename, 'w') as output_file:
            write_header(output_file)
            for location in all_locations:
                output_file.write(get_kml(location))
            write_footer(output_file)
    

    【讨论】:

    • 看起来干净多了。我没有足够的精力将代码重写为惯用的 python!
    • 非常感谢你们!我认为三个“”“只是为了评论。(我现在使用 Python)。我已经修改了页眉和页脚部分,但现在得到错误“回溯(最近一次调用最后一次):文件“C: \Python27\testMap4.py",第 47 行,在 中用于 all_locations 中的位置:文件 "C:\Python27\testMap4.py",第 43 行,在 all_locations = (location_info(*line[0:6 ]) for line in csv_reader) # 切片是由于尾随;ValueError: I/O operation on closed file' 有什么想法吗?再次感谢。
    • 您的缩进是否正确?缩进在 python 中是有意义的,并且 input_file 只在以with open(input_filename) as input_file:开始的块内打开
    • 啊,是的,对不起......当我运行它时,它抱怨缩进,所以我改变了它。改回来后,我现在得到'NameError:name 'f' is not defined'。我认为它可能需要是 'output_file.write(get_kml(location))' 但后来我收到错误 'NameError: name 'get_kml' is not defined'...我陷入了我自己无知的循环:) 你能帮忙吗?
    • 我没有检查就写了输出部分。我已经修好了。
    【解决方案2】:

    根据文档:

    https://developers.google.com/kml/documentation/kmlreference#point

    KML 文件中的坐标应按经度、纬度顺序排列(这似乎有点违反直觉!)。 你需要翻转它们。

    f.write("           <coordinates>" + str(LON) + "," + str(LAT) + "</coordinates>\n")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-05
      • 2017-08-30
      • 2013-07-20
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多