如何将python dict转换为格式标准的geojson文件?

如何将python dict转换为格式标准的geojson文件?,python,dictionary,geojson,Python,Dictionary,Geojson,我想将excel文件转换为geojson文件。字典是这样的: [ {"NoAdresse": 42537006584, "NoUsager": 42537000086, "LatEffective": 45.83675, "LongDebut": 4.91956, "LatDebut": 45.75529, "LongEffective": 4.84574, "IdVehicule": "246Veh", "LatArrivee": 45.83492, "NoDemande": 42537000

我想将excel文件转换为geojson文件。字典是这样的:

[
{"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}]
我使用这段代码来实现这一点:

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)
然后我想将其转换为geojson文件,格式如下:

{ "type": "FeatureCollection",
"features": [{ 
    "type": "Feature",
    "geometry": {
        "type": "LineString",
        "coordinates": [[LatDebut, LongDebut],[LatEffective,LongEffective]]
    },
    "properties": {
        "NoAdresse": "XXX",
        "NoUsager": "XXX",
        "NoDemand":"XXX",
        "IdVehicule":"XXX"
    }
}, { 
...
}]
}
我不知道怎么做,也不知道是否有其他方法可以直接从excel转换为geojson文件。此外,我想添加一个属性“Tour”,每次“idvehicleue”更改时它都会更改。我知道这要求太多了,但我被困了这么久,任何帮助都将不胜感激


谢谢

这里有一个包[geojson][1]:。

所以如果你知道如何将dict“按摩”到你想要的最终结构中——将所有的“其他元素”移动到一些属性成员中——那么我想这就很简单了

# work on dict_list to produce some dict_in_geojson_form
# ... then:
with open('data.json','w') as f:
    json.dump(dict_in_geojson_form, f)
如果序列化仍然不清楚,您可能还需要查看或

高级更新:根据修改后的请求,添加一些简单的转换和巡更枚举。请参阅下面的示例代码(在不同的代码框中拆分,以便不必滚动…:

#! /usr/bin/env python
"""Map a specific stream to seom GeoJSON target structure and stream the
output in chunks as elements are complete (any new vehicle id increments
the tour label which works like an enumeration in the properties of the
features GeoJSON representation)."""
from __future__ import print_function

import copy
import json
import sys
#一些用于限制文字和准备结构的声明 #一种简单的特征发射源模拟 #无上下文转换: #分离的特性发射器(这里的杀伤力过大,但是…) #用于共享巡更的要素序列的上下文感知生成器 #模拟函数将输出传输到标准输出或文件。。。 #驱动转换的样本处理逻辑 #…此处为写入硬编码文件路径的示例 处理中的想法应该在文档字符串中

还可以收集/聚合/过滤每个车辆ID的坐标,或者…它是一种通用编程语言;-)

在我的机器上,yumyum.txt内的输出为:

$ cat yumyum.geojson 
{
"type": "FeatureCollection",
"features": [
{"geometry": {"coordinates": [[45.75529, 4.91956], [45.83675, 4.84574]], "type": "LineString"}, "properties": {"IdVehicule": "246Veh", "NoAdresse": 42537006584, "NoDemande": 42537000003, "NoUsager": 42537000086, "Tour": 1}, "type": "Feature"},
{"geometry": {"coordinates": [[45.83675, 4.84574], [45.83955, 4.83098]], "type": "LineString"}, "properties": {"IdVehicule": "246Veh", "NoAdresse": 42537007718, "NoDemande": 42537000004, "NoUsager": 42537002720, "Tour": 1}, "type": "Feature"},
{"geometry": {"coordinates": [[45.72941, 4.88396], [45.69349, 4.94466]], "type": "LineString"}, "properties": {"IdVehicule": "164Veh", "NoAdresse": 42537000007, "NoDemande": 42537000070, "NoUsager": 42537002425, "Tour": 2}, "type": "Feature"}]
}

我已经拿到这个包裹了。但我的问题更多的是如何转换现有的数据,而不是每一个数据都输入!您的问题可能会受益于更详细的信息和带有实数的小样本,以了解哪里需要一对一和哪里需要“聚合”映射。基本上,上面的代码似乎生成了一个data.json文件,但您需要“一些”geojson映射的json文件。对吗?因此,我建议您直接使用dict_list,而不是将其json序列化为字符串,然后将其写入文件,而是直接将json序列化转储到文件。因此,请添加一个具体的示例输入dict部分a(和b?…)应映射到geojson建模部分/整个z。谢谢事实上,这是真实的数字。这是关于客户及其坐标的数字。第一部分已经是字典了。如何直接将其转储到文件?除了坐标部分,所有其他部分都将进入geojsonOk中的“属性”,如果我现在正确理解了这一点,我希望我提供的答案能有所帮助。如果我误解了这个问题,请在这里发表评论。谢谢,“按摩”,其实是我的问题。我不知道如何移动元素。以及如何在dict中将两个“键”设置为坐标点?我假设不必手动键入所有内容,但结果返回null。{}当“IDVehicleue”=246时,“Tour”计数1,当“IDVehicleue”=164时,“Tour”计数2。这是它的总体思路。所以“巡更”将是每个车辆id的功能计数,但它放在哪里呢?作为处理脚本“打印”或注入GeoJSON(确切位置)的信息,它用于识别不同的骑行(或旅程)。我想它会作为信息出现在“属性”部分。@ch36r5s请检查我的答案现在是否与更新/修订的问题相匹配。如果是,请将其标记为已接受,否则请发表评论。谢谢
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
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
def feature_gen(events):
    """Generator creates features from events (might be a good place
    to hook into validty checks in real lif processing)."""
    for event in events:
        yield feature_from(event)
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
def geojson_out(text, stream=sys.stdout):
    """Expected JSON text is output here."""
    stream.write(text)
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 elememt).
    """
    with open('yumyum.geojson', 'wt') as f_out:
        geojson_out(GEOJSON_FRAME_PREFIX, stream=f_out)
        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_out)
                geojson_out(json.dumps(feature, sort_keys=True), stream=f_out)
                json_array_nanny_needed = True  # HACK A DID ACK

        geojson_out(GEOJSON_FRAME_POSTFIX, stream=f_out)

if __name__ == '__main__':
    main()
$ cat yumyum.geojson 
{
"type": "FeatureCollection",
"features": [
{"geometry": {"coordinates": [[45.75529, 4.91956], [45.83675, 4.84574]], "type": "LineString"}, "properties": {"IdVehicule": "246Veh", "NoAdresse": 42537006584, "NoDemande": 42537000003, "NoUsager": 42537000086, "Tour": 1}, "type": "Feature"},
{"geometry": {"coordinates": [[45.83675, 4.84574], [45.83955, 4.83098]], "type": "LineString"}, "properties": {"IdVehicule": "246Veh", "NoAdresse": 42537007718, "NoDemande": 42537000004, "NoUsager": 42537002720, "Tour": 1}, "type": "Feature"},
{"geometry": {"coordinates": [[45.72941, 4.88396], [45.69349, 4.94466]], "type": "LineString"}, "properties": {"IdVehicule": "164Veh", "NoAdresse": 42537000007, "NoDemande": 42537000070, "NoUsager": 42537002425, "Tour": 2}, "type": "Feature"}]
}