txt转换为geojson
import json
f_in = open("/Users/XXXXX/Desktop/aoi_samples.txt", "r", encoding="utf-8-sig")
input_data = f_in.readlines()
geojson = '{"type":"FeatureCollection","features":['
for num, row in enumerate(input_data):
seg_row = row.strip("\r\n").split("\t")
seg_length = len(seg_row)
# 取header列信息,并找到geom的位置供后续处理使用
if num == 0:
tag_set = seg_row
geom_loc = tag_set.index("Geom")
else:
# 将所有properties整合到dict中,最后直接导出json格式
dict_tmp = {}
for i in range(0,seg_length):
dict_tmp[tag_set[i]] = seg_row[i]
# geometry构造
geom = seg_row[geom_loc].split(" (")
geom_type = geom[0]
if geom_type == "POLYGON":
geom_set = geom[1][1:-2].split(", ")
geom_coor = [[]]
for tmp_geom in geom_set:
geom_x = float(tmp_geom.split(" ")[0])
geom_y = float(tmp_geom.split(" ")[1])
geom_coor[0].append([geom_x, geom_y])
else:
geom_xy = geom[1][:-1].split(" ")
geom_coor = [float(geom_xy[0]), float(geom_xy[1])]
# 输出最终结果, ensure_ascii=False使中文能正常显示
geojson += '{"type":"Feature","geometry":{"type":"%s","coordinates":%s},"properties":%s},\n' \
% (geom_type, geom_coor, json.dumps(dict_tmp, ensure_ascii=False))
geojson = geojson[:-2] + '\n]}'
geojson_file = open('/Users/XXXXX/Desktop/aoi_samples.geojson', 'w')
geojson_file.writelines(geojson)
修改路径后就能直接使用,非常方便,需要头文件,且有Geom标示坐标
其中,使用到json.dumps,其中的参数参考如下文章,写的非常完整
https://www.jianshu.com/p/cfbcd9f8691c