如何将Python字典转换为符合标准格式的GeoJSON文件?
如何将Python字典转换为符合标准格式的GeoJSON文件?
我想要将一个Excel文件转换成GeoJSON文件。字典的格式如下:\n
[ {"NoAdresse": 42537006584, "NoUsager": 42537000086, "LatEffective": 45.83675, "LongDebut": 4.91956, "LatDebut": 45.75529, "LongEffective": 4.84574, "IdVehicule": "246Veh", "LatArrivee": 45.83492, "NoDemande": 42537000003, "LongArrivee": 4.84762}, {"NoAdresse": 42537007718, "NoUsager": 42537002720, "LatEffective": 45.83955, "LongDebut": 4.84574, "LatDebut": 45.83675, "LongEffective": 4.83098, "IdVehicule": "246Veh", "LatArrivee": 45.83935, "NoDemande": 42537000004, "LongArrivee": 4.83084}, {"NoAdresse": 42537005803, "NoUsager": 42537002424, "LatEffective": 45.98730, "LongDebut": 4.83098, "LatDebut": 45.83955, "LongEffective": 4.72695, "IdVehicule": "246Veh", "LatArrivee": 45.98174, "NoDemande": 42537000006, "LongArrivee": 4.73942}, {"NoAdresse": 42537005803, "NoUsager": 42537003576, "LatEffective": 45.98730, "LongDebut": 4.83098, "LatDebut": 45.83955, "LongEffective": 4.72695, "IdVehicule": "246Veh", "LatArrivee": 45.98174, "NoDemande": 42537000005, "LongArrivee": 4.73942}, {"NoAdresse": 42537004215, "NoUsager": 42537003576, "LatEffective": 45.93778, "LongDebut": 4.72695, "LatDebut": 45.9873, "LongEffective": 4.62676, "IdVehicule": "246Veh", "LatArrivee": 45.93784, "NoDemande": 42537000005, "LongArrivee": 4.62625}, {"NoAdresse": 42537004215, "NoUsager": 42537002424, "LatEffective": 45.93778, "LongDebut": 4.72695, "LatDebut": 45.9873, "LongEffective": 4.62676, "IdVehicule": "246Veh", "LatArrivee": 45.93784, "NoDemande": 42537000006, "LongArrivee": 4.62625}, {"NoAdresse": 42537004215, "NoUsager": 42537002720, "LatEffective": 45.93778, "LongDebut": 4.72695, "LatDebut": 45.9873, "LongEffective": 4.62676, "IdVehicule": "246Veh", "LatArrivee": 45.93784, "NoDemande": 42537000004, "LongArrivee": 4.62625}, {"NoAdresse": 42537004215, "NoUsager": 42537000086, "LatEffective": 45.93778, "LongDebut": 4.72695, "LatDebut": 45.9873, "LongEffective": 4.62676, "IdVehicule": "246Veh", "LatArrivee": 45.93784, "NoDemande": 42537000003, "LongArrivee": 4.62625}, {"NoAdresse": 42537000007, "NoUsager": 42537002425, "LatEffective": 45.72941, "LongDebut": 4.77845, "LatDebut": 45.77335, "LongEffective": 4.88396, "IdVehicule": "164Veh", "LatArrivee": 45.72815, "NoDemande": 42537000070, "LongArrivee": 4.88241}, {"NoAdresse": 42537000007, "NoUsager": 42537002425, "LatEffective": 45.69349, "LongDebut": 4.88396, "LatDebut": 45.72941, "LongEffective": 4.94466, "IdVehicule": "164Veh", "LatArrivee": 45.69429, "NoDemande": 42537000070, "LongArrivee": 4.94216}]
\n我使用以下代码来实现这个功能:\n
import json from xlrd import open_workbook book = open_workbook('forum.xlsx') sheet = book.sheet_by_index(0) keys = [sheet.cell(0,col_index).value for col_index in xrange(sheet.ncols)] dict_list = [] for row_index in xrange(1,sheet.nrows): d = {keys[col_index]: sheet.cell(row_index,col_index).value for col_index in xrange(sheet.ncols)} dict_list.append(d) j = json.dumps(dict_list) with open('data.json','w') as f: f.write(j)
\n然后我想要将其转换成以下形式的GeoJSON文件:\n{ \"type\": \"FeatureCollection\",\n\"features\": [{ \n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"LineString\",\n \"coordinates\": [[LatDebut, LongDebut],[LatEffective,LongEffective]]\n },\n \"properties\": {\n \"NoAdresse\": \"XXX\",\n \"NoUsager\": \"XXX\",\n \"NoDemand\":\"XXX\",\n \"IdVehicule\":\"XXX\"\n }\n}, { \n...\n}]\n}\n
\n我不知道如何做到这一点,也不知道是否有其他直接从Excel转换成GeoJSON文件的方法。此外,我想要添加一个名为\"Tour\"的属性,每当\"IdVehicule\"改变时,它也会改变。我知道这是要求很多,但我已经卡住很久了,非常感谢任何帮助。谢谢。
如何将Python字典转换为标准形式的GeoJSON文件?
最近,我遇到了将Python字典转换为GeoJSON文件的问题。我知道有一个名为"geojson"的包可以用来处理GeoJSON数据,但是我遇到了一些困难。我的问题并不是在手动键入每个数据项,而是如何使用现有数据进行转换。
幸运的是,我找到了一个解决方法。首先,我需要确保已经安装了"geojson"包。如果没有安装,可以在这里找到包的链接:[geojson](https://github.com/frewsxcv/python-geojson)。
一旦安装了"geojson"包,我就可以开始将Python字典转换为GeoJSON文件。下面是解决方法的代码示例:
import geojson # 创建一个包含要转换的数据的Python字典 data = { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "name": "City 1", "population": 100000 }, "geometry": { "type": "Point", "coordinates": [0, 0] } }, { "type": "Feature", "properties": { "name": "City 2", "population": 200000 }, "geometry": { "type": "Point", "coordinates": [1, 1] } } ] } # 将Python字典转换为GeoJSON对象 geojson_object = geojson.FeatureCollection(data['features']) # 将GeoJSON对象写入文件 with open('output.geojson', 'w') as f: geojson.dump(geojson_object, f)
在上面的代码中,我首先创建了一个包含要转换的数据的Python字典。然后,我使用"geojson.FeatureCollection"函数将Python字典转换为GeoJSON对象。最后,我使用"geojson.dump"函数将GeoJSON对象写入名为"output.geojson"的文件中。
通过这种方式,我可以将Python字典转换为标准形式的GeoJSON文件。这个解决方法非常简单,而且使用了"geojson"包的功能。
总结一下,要将Python字典转换为标准形式的GeoJSON文件,可以使用"geojson"包。首先,确保已经安装了该包。然后,使用"geojson.FeatureCollection"函数将Python字典转换为GeoJSON对象。最后,使用"geojson.dump"函数将GeoJSON对象写入文件。这样,我们就可以轻松地将Python字典转换为标准形式的GeoJSON文件了。
如何将Python字典转换为标准格式的GeoJSON文件?
问题的出现原因:
我不知道如何将字典中的元素移动到所需的最终结构中,并且不知道如何将两个键值对转换为一个坐标点。
解决方法:
可以按照以下步骤进行处理:
1. 将字典转换为标准的GeoJSON格式。
2. 为每个不同的"IdVehicule"(车辆ID)计算"Tour"(行程)的数量。
3. 将转换后的结果写入文件。
以下是示例代码:
from __future__ import print_function import copy import json import sys # Some declarations to confine literals and prepare structure NO_ADDRESS = 'NoAdresse' NO_USAGE = 'NoUsager' ID_VEHICLE = 'IdVehicule' NO_DEMAND = 'NoDemande' TOUR_LABEL = 'Tour' PROPERTY_KEYS = (NO_ADDRESS, NO_USAGE, ID_VEHICLE, NO_DEMAND) LAT_DEBUT = 'LatDebut' LONG_DEBUT = 'LongDebut' LAT_EFFECTIVE = 'LatEffective' LONG_EFFECTIVE = 'LongEffective' COORD_KEYS_DEBUT = (LAT_DEBUT, LONG_DEBUT) COORD_KEYS_EFFECTIVE = (LAT_EFFECTIVE, LONG_EFFECTIVE) PROPERTIES_KEY = 'properties' GEOMETRY_KEY = 'geometry' COORDINATES_KEY = 'coordinates' FEATURES_KEY = 'features' GEOJSON_FRAME_PREFIX = """{ "type": "FeatureCollection", "features": [ """ FEATURE_TEMPLATE = { "type": "Feature", GEOMETRY_KEY: { "type": "LineString", "coordinates": [] }, "properties": { NO_ADDRESS: None, NO_USAGE: None, NO_DEMAND: None, ID_VEHICLE: None, TOUR_LABEL: None }} GEOJSON_LIST_SEP = ',\n' GEOJSON_FRAME_POSTFIX = ']\n}\n' # A simple feature emitting source mock def event_source(): """Sample input line source generator. Might anything yielding python dictionaries matching "this questions" event specification.""" event_seq = [ {NO_ADDRESS: 42537006584, NO_USAGE: 42537000086, LAT_EFFECTIVE: 45.83675, LONG_DEBUT: 4.91956, LAT_DEBUT: 45.75529, LONG_EFFECTIVE: 4.84574, ID_VEHICLE: "246Veh", "LatArrivee": 45.83492, NO_DEMAND: 42537000003, "LongArrivee": 4.84762}, {NO_ADDRESS: 42537007718, NO_USAGE: 42537002720, LAT_EFFECTIVE: 45.83955, LONG_DEBUT: 4.84574, LAT_DEBUT: 45.83675, LONG_EFFECTIVE: 4.83098, ID_VEHICLE: "246Veh", "LatArrivee": 45.83935, NO_DEMAND: 42537000004, "LongArrivee": 4.83084}, {NO_ADDRESS: 42537000007, NO_USAGE: 42537002425, LAT_EFFECTIVE: 45.69349, LONG_DEBUT: 4.88396, LAT_DEBUT: 45.72941, LONG_EFFECTIVE: 4.94466, ID_VEHICLE: "164Veh", "LatArrivee": 45.69429, NO_DEMAND: 42537000070, "LongArrivee": 4.94216}] for event in event_seq: yield event # The context free transformations: def feature_from(event): """Transform event to feature, applying the "business" rules.""" feature = copy.deepcopy(FEATURE_TEMPLATE) for property_key in PROPERTY_KEYS: feature[PROPERTIES_KEY][property_key] = event[property_key] coords_debut = [event[k] for k in COORD_KEYS_DEBUT] coords_effective = [event[k] for k in COORD_KEYS_EFFECTIVE] feature[GEOMETRY_KEY][COORDINATES_KEY].append(coords_debut) feature[GEOMETRY_KEY][COORDINATES_KEY].append(coords_effective) return feature # The separated emitter of features (overkill here, but ...) def feature_gen(events): """Generator creates features from events (might be a good place to hook into validity checks in real life processing).""" for event in events: yield feature_from(event) # The context aware generator for feature sequences sharing a tour def tour_gen(features): """Generator emits the feature in chunks per complete tour as detected by a change in vehicle id.""" id_vehicle_active = None tour_enumeration = None for feature in features: id_vehicle_received = feature[PROPERTIES_KEY][ID_VEHICLE] if id_vehicle_active is None: id_vehicle_active = id_vehicle_received tour_enumeration = 1 tour = [] if id_vehicle_active != id_vehicle_received: yield tour tour = [] tour_enumeration += 1 id_vehicle_active = id_vehicle_received feature[PROPERTIES_KEY][TOUR_LABEL] = tour_enumeration tour.append(feature) else: feature[PROPERTIES_KEY][TOUR_LABEL] = tour_enumeration tour.append(feature) if tour: yield tour # Mock function to channel the output to stdout or file ... def geojson_out(text, stream=sys.stdout): """Expected JSON text is output here.""" stream.write(text) # Sample processing logic driving the transformation def main(): """Poor man's streaming falls back on hardcoded GeoJSON "frame" string as pre and post fix to the feature stream. the latter elements are accumulated in chunks carrying common "tour" enumeration label. The frame structure in Python lingo is: geo_dict = {"type": "FeatureCollection", "features": []} The features will be injected in the list and in this implementation need some stateful separator injection hack, to yield valid JSON (which does not allow trailing comma after last array element). """ with open('data.json', 'w') as f: geojson_out(GEOJSON_FRAME_PREFIX, stream=f) json_array_nanny_needed = False # Semi-auto, means semi-manual =( for features in tour_gen(feature_gen(event_source())): for feature in features: if json_array_nanny_needed: geojson_out(GEOJSON_LIST_SEP, stream=f) geojson_out(json.dumps(feature, sort_keys=True), stream=f) json_array_nanny_needed = True # HACK A DID ACK geojson_out(GEOJSON_FRAME_POSTFIX, stream=f) if __name__ == '__main__': main()
以上就是将Python字典转换为标准格式的GeoJSON文件的解决方法。通过以上代码,可以将字典转换为GeoJSON文件,并且每个不同的"IdVehicule"(车辆ID)会计算一个"Tour"(行程)的数量。最后,将转换后的结果写入文件。