Skip to content

Instantly share code, notes, and snippets.

@jurand71
Created August 23, 2022 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jurand71/4dbdfee9eb96f7eec4c01ecdfe763cc9 to your computer and use it in GitHub Desktop.
Save jurand71/4dbdfee9eb96f7eec4c01ecdfe763cc9 to your computer and use it in GitHub Desktop.
port pandas as pd
import requests
from bs4 import BeautifulSoup
url='https://pl.wikisource.org/wiki/Polskie_powiaty_wed%C5%82ug_kodu_TERYT'
page = requests.get(url)
soup = BeautifulSoup(page.text,'html.parser')
table = soup.find_all('table')[3]
powiaty_teryt_df = pd.read_html(str(table))
powiaty_teryt_df = pd.DataFrame(powiaty_teryt_df[0])
powiaty_teryt_df.columns = ['Nazwa_powiatu','Kod_TERYT']
powiaty_teryt_df['Nazwa_powiatu'] = powiaty_teryt_df['Nazwa_powiatu'].str.replace('m. ','', regex=False)
powiaty_teryt_df['Nazwa_powiatu'] = powiaty_teryt_df['Nazwa_powiatu'].str.replace(r'\s(.*)','',regex=True)
url='https://pl.wikipedia.org/wiki/Wojew%C3%B3dztwo'
page = requests.get(url)
soup = BeautifulSoup(page.text,'html.parser')
table = soup.find('table',{'class':"wikitable"})
wojewodztwa_teryt_df = pd.read_html(str(table))
wojewodztwa_teryt_df = pd.DataFrame(wojewodztwa_teryt_df[0])
wojewodztwa_teryt_df = wojewodztwa_teryt_df.iloc[:,:2]
wojewodztwa_teryt_df.columns = ['Kod_TERYT','Nazwa_wojewodztwa']
wojewodztwa_teryt_df['Kod_TERYT'] = wojewodztwa_teryt_df['Kod_TERYT'].str.replace(r'\s(.*)','',regex=True)
miejscowosci_df = pd.read_csv('SIMC_miejscowosci_baza.csv')
miejscowosci_df = miejscowosci_df.iloc[:,[0,1,6]]
miejscowosci_df['WOJ'] = miejscowosci_df['WOJ'].apply(str).str.rjust(2, "0")
miejscowosci_df['POW'] = miejscowosci_df['POW'].apply(str).str.rjust(2, "0")
miejscowosci_df['Kod_TERYT'] = miejscowosci_df['WOJ'] + ' ' + miejscowosci_df['POW']
places_df = miejscowosci_df.merge(powiaty_teryt_df, left_on='Kod_TERYT', right_on='Kod_TERYT', how='left')
places_df = places_df.merge(wojewodztwa_teryt_df, left_on='WOJ', right_on='Kod_TERYT', how='left')
places_df = places_df.iloc[:,[2,4,6]]
places_df.columns = ['city','county','state']
places_df = places_df.drop_duplicates()
# geocoding with Nominatim
import urllib.parse
import http.client
import json
def api_call(host, base_url, headers, params):
try:
conn = http.client.HTTPSConnection(host)
conn.request("GET", base_url + "?%s" %params, "{body}", headers)
response = conn.getresponse()
data = json.loads(response.read())
conn.close()
return data
except Exception as e:
print("[Error {0}] {1}".format(e.errno, e.strerror))
return None
def get_lat_long(city, county, state, country):
params = urllib.parse.urlencode({'city': city,
'county': county,
'state': state,
'country': country,
'format': 'json' })
headers = { 'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate',
'Accept': '/', 'Connection': 'keep-alive' }
r = api_call("nominatim.openstreetmap.org", "/search", headers, params)
return float(r[0]['lat']), float(r[0]['lon']), int(r[0]['place_id']), int(r[0]['osm_id']), str(r[0]['display_name'])
def get_lat_long_place(city, county, state):
try:
return get_lat_long(city, county, state, 'Polska')
except:
return None, None
location = places_df.apply(lambda x: get_lat_long_place(x.city,x.county,x.state), axis=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment