Created
October 19, 2016 07:23
-
-
Save cquest/4b7fb76f5a02edbba70897953623ae31 to your computer and use it in GitHub Desktop.
geocode CSV files using addok
This file contains hidden or 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
| import csv | |
| import sys | |
| import requests | |
| import json | |
| # Usage: python csv2geocode.py inputcsv inputcols geo_cols | |
| # Ex: python csv2geocode.py example.csv numero,voie,codep,ville longitude,latitude,score,type,label,citycode | |
| cols = sys.argv[2].split(',') | |
| print(cols) | |
| # columns to keep from geocoding result | |
| if len(sys.argv)>=3: | |
| geo_cols = sys.argv[3].split(',') | |
| else: | |
| geo_cols = ['longitude','latitude','score','type','label','id','citycode'] | |
| # open input and output files | |
| reader = csv.reader(open(sys.argv[1])) | |
| writer = csv.writer(sys.stdout) | |
| header_input = None | |
| for row in reader: | |
| # csv header line | |
| if header_input is None: | |
| header_input = row | |
| header_output = header_input | |
| for col in geo_cols: | |
| header_output.append(col) | |
| writer.writerow(header_output) | |
| else: | |
| addr = '%s %s %s %s' % (row[0], row[1], row[2], row[3]) | |
| params = {'q': addr, 'limit':1, 'autocomplete':'false'} | |
| r = requests.get('http://api-adresse.data.gouv.fr/search/', params=params) | |
| geocode = json.loads(r.text) | |
| geocode = geocode['features'][0] | |
| for col in geo_cols: | |
| if col=='longitude': | |
| row.append(geocode['geometry']['coordinates'][0]) # longitude | |
| elif col=='latitude': | |
| row.append(geocode['geometry']['coordinates'][1]) # latitude | |
| else: | |
| row.append(geocode['properties'][col]) | |
| writer.writerow(row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment