解析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)