extract_universities.py 1.7 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python3

"""
Script to insert the country data in the database

IT HAS TO BE RUN INSIDE ./manage.py shell
"""
import csv 
import os
import time
from geopy.geocoders import Nominatim

tmp = os.path.join(os.path.realpath(__file__), '../../assets/destinations.csv')
destinations_path = os.path.abspath(tmp)

tmp = os.path.join(os.path.realpath(__file__), '../../assets/destinations_extracted.csv')
destinations_extracted_path = os.path.abspath(tmp)

if not os.path.isfile(destinations_path):
    print(destinations_path)
    raise Exception("Missing file containing country data")

with open(destinations_path, 'rt') as input:
    with open(destinations_extracted_path, 'w') as output:
        print("ini")
        reader = csv.reader(input)
        spamwriter = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
        geolocator = Nominatim()

        failed = []
        i = 0
        for row in reader:
            # handle the header
            if i == 0:
                header = ['University', 'lat', 'lon']
                spamwriter.writerow(header)
                i += 1
            else:
                query = row[2]#+ ', ' + row[1] + ', ' + row[0]
                
                while True:
                    try:
                        location = geolocator.geocode(query)
                        break
                    except:
                        print("error during query, retrying")
                        time.sleep(1)

                print(location)
                if location is not None:
                    spamwriter.writerow([row[2], location.latitude, location.longitude])
                else:
                    failed.append(query)
        
        print(failed)