Created
August 5, 2016 19:45
-
-
Save brizandrew/99ab96d68e3aefe752309956e0e265da to your computer and use it in GitHub Desktop.
This file contains 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
from geopy.geocoders import Nominatim | |
from geopy.exc import GeocoderServiceError, GeocoderTimedOut | |
""" | |
@function getZipCode | |
Finds the zip code given a Cincinnati, OH address | |
@param {str} addressStreet: The address to find the zip code of | |
@return {str}: The zip code or an empty string if no zip code is found. | |
""" | |
def getZipCode(addressStreet): | |
zipCodeFound = False | |
# Start a loop to retry incase there are geopy errors | |
while not zipCodeFound: | |
try: | |
# Create a new geolocator and pass it the address | |
geolocator = Nominatim() | |
geolocation = geolocator.geocode(addressStreet + ', Cincinnati OH') | |
# If it returns a geolocation object | |
if geolocation is not None: | |
# Split the address string by commas | |
addressArr = geolocation.address.split(', ') | |
zipcode = None | |
# Go through each item in the address array | |
for item in addressArr: | |
# If it's 5 or 10 characters long... | |
if len(item) == 5 or len(item) == 10: | |
allCharsAreNumbers = True | |
# Go through each character in that item | |
for char in item: | |
# If they're all numbers or a dash, you've found the zipcode | |
if not isNumber(char) and char != '-': | |
allCharsAreNumbers = False | |
break | |
if allCharsAreNumbers: | |
zipcode = item | |
zipCodeFound = True | |
# If there was no geolocation object returned, zipcode is an empty string | |
else: | |
zipcode = '' | |
zipCodeFound = True | |
# If there are the following errors, try again... | |
except GeocoderTimedOut: | |
pass | |
except GeocoderServiceError: | |
pass | |
return zipcode.strip() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment