我需要一个 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)
非常感谢任何帮助!
最佳答案
可以直接使用 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)
关于将 CSV 转换为 GeoJSON 的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48586647/