代码之家  ›  专栏  ›  技术社区  ›  user5834454

将CSV转换为GeoJSON的Python脚本

  •  9
  • user5834454  · 技术社区  · 6 年前

    我需要一个Python脚本将CSV数据转换为GeoJSON输出。输出应符合以下格式:

    {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates":  [ -85.362709,40.466442 ]
          },
          "properties": {
            "weather":"Overcast",
            "temp":"30.2 F"
          }
        }
      ]
    }
    

    我正在使用此脚本运行该进程,但它不会生成所需的输出:

    import csv, json
        li = []
        with open('CurrentObs.csv', newline='') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            for latitude, longitude, weather, temp in reader:
                li.append({
                   "latitude": latitude,
                   "longitude": longitude,
                   "weather": weather,
                   "temp": temp,
                   "geo": {
                        "__type": "GeoPoint",
                        "latitude": latitude,
                        "longitude": longitude,
                    }
                })
    
        with open("GeoObs.json", "w") as f:
            json.dump(li, f)
    

    非常感谢您的帮助!

    2 回复  |  直到 6 年前
        1
  •  15
  •   ewcz    6 年前

    可以直接使用 geojson 包裹:

    import csv, json
    from geojson import Feature, FeatureCollection, Point
    
    features = []
    with open('CurrentObs.csv', newline='') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for latitude, longitude, weather, temp in reader:
            latitude, longitude = map(float, (latitude, longitude))
            features.append(
                Feature(
                    geometry = Point((longitude, latitude)),
                    properties = {
                        'weather': weather,
                        'temp': temp
                    }
                )
            )
    
    collection = FeatureCollection(features)
    with open("GeoObs.json", "w") as f:
        f.write('%s' % collection)
    
        2
  •  4
  •   wallace manzano    6 年前

    检查此脚本是否解析

    import csv
    import json
    from collections import OrderedDict
    
    li = []
    with open('CurrentObs.csv', 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for latitude, longitude, weather, temp in reader:
            d = OrderedDict()
            d['type'] = 'Feature'
            d['geometry'] = {
                'type': 'Point',
                'coordinates': [float(latitude), float(longitude)]
            }
            d['properties'] = {
                'weather': weather,
                'temp': temp
            }
            li.append(d)
    
    d = OrderedDict()
    d['type'] = 'FeatureCollection'
    d['features'] = li
    with open('GeoObs.json', 'w') as f:
        f.write(json.dumps(d, sort_keys=False, indent=4))