Created
May 18, 2021 14:29
-
-
Save Stimim/d115cc7c0ac6db416be22a618cff1cba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
import csv | |
import json | |
def ConvertGeoJsonToWebsiteFormat(geojson): | |
if geojson.get('type') != 'FeatureCollection': | |
return [] | |
features = geojson.get('features', []) | |
return_value = [] | |
for feature in features: | |
if feature.get('type') != 'Feature': | |
continue | |
geometry = feature.get('geometry', {}) | |
if not geometry: | |
continue | |
properties = feature.get('properties', {}) | |
name = properties.get('name') | |
if not name: | |
continue | |
source = properties.get('資料來源') | |
if not source: | |
print(name) | |
continue | |
begin = properties.get('begin', None) | |
end = properties.get('end', None) | |
try: | |
if not begin or not end or not (begin < end): | |
print(f'invalid feature: {feature}') | |
continue | |
except Exception: | |
print(f'invalid feature: {feature}') | |
continue | |
return_value.append(feature) | |
return return_value | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--input', '-i', default='input.csv') | |
parser.add_argument('--output', '-o', default='output.geojson') | |
args = parser.parse_args() | |
with open(args.input) as csvfile: | |
reader = csv.reader(csvfile) | |
headers = next(reader) | |
# print(headers) | |
all_features = [] | |
for row in reader: | |
d = dict(zip(headers,row)) | |
geojson_string = d.get('GeoJSON', '') | |
if not geojson_string: | |
continue | |
geojson = json.loads(geojson_string) | |
converted_data = ConvertGeoJsonToWebsiteFormat(geojson) | |
if not converted_data: | |
continue | |
all_features += converted_data | |
print(f'Dumping {len(all_features)} records') | |
with open(args.output, 'w') as f: | |
o = { | |
'type': 'FeatureCollection', | |
'features': all_features, | |
} | |
json.dump(o, f, indent=2, sort_keys=True) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment