解析kml文件,提取经纬度信息存入csv

解析kml文件

解析kml文件,读取出经纬度和时间信息,对应好,存入一个csv文件。代码较简单,根据不同需求,稍加修改即可。

里面有几个坑,kml里面Document目标下,如果有除id=…字样外的其他字符,可能提取不到目标,需要删除之。另外,提取关键词,如果含有符号,也会报错,需要提前把关键词里的符号处理下。还有就是提取出的时间信息,需要把前面的一些打卡点的时间信息去掉,然后才能和每一个经纬度坐标信息对应上,即数量上对等。

代码应该还有可以优化的地方,暂没时间弄了,欢迎大家指正。
希望对有同样需求的小伙伴有所帮助。

from pykml import parser
import pandas as pd
import os

OriPath = './files/'
CsvPath = './CSV/'
TmpPath = './tmptxt/'

names = os.listdir(OriPath)

for name in names:
    n = name[0:-4]
    FilePath = OriPath + name
    print(f'dealing {name}')

    # 处理格式,重新保存
    txt = open(FilePath, 'r', encoding="utf-8")
    txt = txt.read().replace('xmlns=""', '')
    txt = txt.replace('gx:Track', 'gxTrack')
    txt = txt.replace('gx:coord', 'gxcoord')

    file = open(FilePath, 'w', encoding='utf-8')
    file.write(txt)
    file.close()

    # 重新读取作为kml解析
    with open(FilePath, 'r', encoding="utf-8") as f:
        kml = parser.parse(f).getroot()

    # 提取坐标&海拔,写入txt
    gxcoord = kml.findall('.//{http://www.opengis.net/kml/2.2}gxcoord')
    len_gx = len(gxcoord)
    geo = str()

    for each in gxcoord:
        geo = geo + each.text + '\n'

    geo_output = open(TmpPath + n + '_geo.txt', 'w', encoding='utf-8')
    geo_output.write(geo)
    geo_output.close()

    # 提取时间,写入txt
    when = kml.findall('.//{http://www.opengis.net/kml/2.2}when')
    len_when = len(when)
    time = str()

    diff = len_when - len_gx
    when = when[diff:]

    for each in when:
        time = time + each.text + '\n'
        time = time.replace('T', ' ')
        time = time.replace('Z', '')

    time_output = open(TmpPath + n + '_time.txt', 'w', encoding='utf-8')
    time_output.write(time)
    time_output.close()

    # 读取出时间和geo的txt数据进合并,输出csv
    df_time = pd.read_csv(TmpPath + n + '_time.txt', header=None, names=['time'])
    df_geo = pd.read_csv(TmpPath + n + '_geo.txt', sep=' ', header=None, names=['Lon', 'Lat', 'altitude'])
    df_cat = pd.concat([df_time, df_geo], axis=1)
    df_cat.drop_duplicates(subset=['time'], keep='first', inplace=True)

    df_cat.to_csv(CsvPath + n + '.csv', index=False)
    
  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值