Skip to content

Instantly share code, notes, and snippets.

@mrinal-scio
Created February 3, 2023 08:12
Embed
What would you like to do?
def clean_address(s):
s1 = re.sub(r'^[A-Z0-9]{4}-', '', s) # T-Mobile specific
s2 = re.sub(r'[^\s,a-zA-Z]', ' ', s1) # drop all numbers and non-comma punct
s3 = re.sub('Remote', '', s2) # drop "Remote"
s4 = re.sub(r'\s+', ' ', s3) # normalize whitespace
return s4.lstrip().rstrip()
def get_city_state_country(location):
API_KEY = "API_KEY"
url = f"https://maps.googleapis.com/maps/api/geocode/json?address={location}&key={API_KEY}"
response = requests.get(url)
data = response.json()
if data["status"] == "OK":
address_components = data["results"][0]["address_components"]
city = state_short = state_long = country = ""
for component in address_components:
if "locality" in component["types"]:
city = component["long_name"]
elif "administrative_area_level_1" in component["types"]:
state_short = component["short_name"]
state_long = component["long_name"]
elif "country" in component["types"]:
country_short = component["short_name"]
country_long = component["long_name"]
country = country_short if country_short in ("US", "UK") else country_long
result_parts = []
if city:
result_parts.append(city)
if state_long:
if country == 'US':
result_parts.append(state_short)
elif not city:
result_parts.append(state_long)
if country:
result_parts.append(country)
return ", ".join(result_parts)
else:
return ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment