-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_citydata.py
More file actions
82 lines (71 loc) · 2.66 KB
/
Copy pathget_citydata.py
File metadata and controls
82 lines (71 loc) · 2.66 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 8 08:54:56 2024
@author: Patrick Hausmann
"""
import pandas as pd
import requests
from bs4 import BeautifulSoup
# --- Custom modules
from get_keys import get_keys
# =============================================================================
# GET CITY LATITUDE, LONGITUDE AND COUNTRY CODE
# =============================================================================
def get_geocoords(cities):
if(type(cities) is str):
cities = [cities]
# --- INITIALIZE NEW DATAFRAME
geocoords = pd.DataFrame({'city':[],
'latitude':[],
'longitude':[],
'country':[]})
# Set query parameters
for i,city in enumerate(cities):
params = {
'q':city,
'appid':get_keys('openweathermap')
}
# Build query URL
url = "http://api.openweathermap.org/geo/1.0/direct?"
# Query API and store response
response = requests.get(url,params).json()[0]
# Transform response to dataframe
res = pd.DataFrame({
'city':city,
'latitude':response['lat'],
'longitude':response['lon'],
'country':response['country']},index=[i])
# Extrend DataFrame
geocoords = pd.concat([geocoords,res])
# Return response
return geocoords
# =============================================================================
# GET CITY POPULATIONS
# =============================================================================
def get_population(cities):
if(type(cities) is str):
cities = [cities]
# Connect to List of cities with over 1 Mio. Inhabitants on Wikipedia
url = "https://en.wikipedia.org/wiki/List_of_cities_with_over_one_million_inhabitants"
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
# Get table from page
citytable = soup.find_all('table')[1].find('tbody').find_all('tr')
# Initialize empty DataFrame
citydata = {}
# --- GO THROUGH CITY TABLE
for i in range(1,len(citytable)):
td = citytable[i].find_all('td')
name = td[0].text.split("\n")[0]
population = int(td[2].text.split("\n")[0].replace(',',''))
citydata[name] = population
# Output population of selected cities
res = [citydata.get(key) for key in cities]
# Output scalar value in case of scalar query
if(len(cities)==1):
res = res[0]
# --- RETURN RESULTS
return res
# TESTING
# cities = ['Berlin','Munich']
# cities = 'Cologne'
# get_population(cities)