def isvalid(self, zipcode): from uszipcode import ZipcodeSearchEngine search = ZipcodeSearchEngine() if zipcode < 90000 or zipcode > 99999 or zipcode == 91980: return False lat = search.by_zipcode(zipcode)['Latitude'] lon = search.by_zipcode(zipcode)['Longitude'] return self.check_SD_lat_lon(lat, lon)
def get_distance_between_zips(zip1, zip2): "Return the distance in miles between two zips" search = ZipcodeSearchEngine() my_zip1 = search.by_zipcode(zip1) loc1 = (my_zip1['Latitude'], my_zip1['Longitude']) my_zip2 = search.by_zipcode(zip2) loc2 = (my_zip2['Latitude'], my_zip2['Longitude']) return vincenty(loc1, loc2).miles
def get_zipcode_crime_map(self, zipcode): """ Generate a html heatmap for the zipcode. """ from uszipcode import ZipcodeSearchEngine search = ZipcodeSearchEngine() zip_lat = search.by_zipcode(zipcode)['Latitude'] zip_lon = search.by_zipcode(zipcode)['Longitude'] self.generate_past_week_html(self.crime_lat_lon_list, center_lat=zip_lat, center_lon=zip_lon)
def city_to_zipcodes(city, state): zipcodeEngineSearch = ZipcodeSearchEngine() try: zipcodes = zipcodeEngineSearch.by_city_and_state(city, state) if not zipcodes: # A zipcode that is known to return null return [zipcodeEngineSearch.by_zipcode(97003)] return zipcodes except ValueError: # A zipcode that is known to return null return [zipcodeEngineSearch.by_zipcode(97003)]
def get_xy_crimeRate_popDensity(self, df): """ Get the relationship between population density and Crime rate, plot in x, y coordinates form """ from uszipcode import ZipcodeSearchEngine search = ZipcodeSearchEngine() crime_rate = [] annual_wage = [] population_dens = [] valid_zip = df['zip'].unique().astype(np.int) crime_num = df.groupby(['zip']).size() for i in valid_zip: if not self.isvalid(i): continue else: wage = search.by_zipcode(i)['Wealthy'] population_den = search.by_zipcode(i)['Density'] rate = crime_num.get(i) / 180.0 if wage is None: continue if rate > 20: print("highest rate: ", i, "rate: ", rate, ", wage: ", wage, " pop desity: ", population_den) if population_den > 12000: print("highest density: ", i, "rate: ", rate, ", wage: ", wage, " pop desity: ", population_den) # a way of measuring good community - dense population, but small crime rate if population_den > 10000 and rate < 4: print("low wage and low crime: ", i, "rate: ", rate, ", wage: ", wage, " pop desity: ", population_den) annual_wage.append(int(wage) * 0.01) crime_rate.append(rate) population_dens.append(population_den) # print(curr_population) plt.scatter(crime_rate, population_dens, s=annual_wage, alpha=0.4) plt.xlabel('Crime Numbers (times / day)') plt.ylabel('Population Density (people / km$^2$)') for income in [10000, 20000, 40000]: plt.scatter([], [], c='k', alpha=0.4, s=income * 0.01, label=str(income) + ' $ / year') plt.legend(scatterpoints=1, frameon=False, labelspacing=1, title='Annual wage') plt.title( 'Crime Rate and Population Density for San Diego Area Zipcodes') plt.show()
def person_searching_teams_result(request): error_message = "" # get and normalize dist dist = int(request.POST['distance']) if dist == None or dist < 1 or dist > max_travel_distance: error_message += "Must specify a distance between 1 and %s miles. " % max_travel_distance dist = 15 zipcode = request.POST['zipcode'] zipcode_search_engine = ZipcodeSearchEngine() info = zipcode_search_engine.by_zipcode(zipcode) latitude = info.Latitude longitude = info.Longitude if latitude == None or longitude == None: error_message += "Must specify a valid US zipcode. " jfll = False if "jfll" in request.POST: jfll = True fll = False if "fll" in request.POST: fll = True ftc = False if "ftc" in request.POST: ftc = True frc = False if "frc" in request.POST: frc = True if not (jfll or fll or ftc or frc): error_message += "Must select at least one of jFLL, FLL, FTC, or FRC type of teams. " new_members = False if "new_members" in request.POST: new_members = True return render_person_searching_teams(request, zipcode, dist, latitude, longitude, new_members, jfll, fll, ftc, frc, error_message)
def get_weatherInfos(weatherData, stationData, stationName): ## find weather available at the station zipcode, if not available in data, find weather at the closest zipcode(s) nearby from geopy.geocoders import Nominatim from uszipcode import ZipcodeSearchEngine geolocator = Nominatim() (lat, lon) = get_station_coordinates(stationName, stationData) location = geolocator.reverse((lat, lon)) zipcode = location.raw['address']['postcode'] search = ZipcodeSearchEngine() zipcode_infos = search.by_zipcode(zipcode) stationWeather = pd.DataFrame() radius = 0 while radius < 10 and stationWeather.shape[0] == 0: zipNearby = [ int(z.Zipcode) for z in search.by_coordinate(lat, lon, radius=radius, returns=5) ] stationWeather = weatherData[weatherData['Zip'].isin(zipNearby)] #print("radius: ", radius) radius += 0.05 ## ?? 50m?, 0.05 miles? print("post codes of neighborhood: ", zipNearby) def fixPrecip(x): try: return float(x) except: return 0.005 # maybe 0.01 or something? precipitation_inch = stationWeather[u'PrecipitationIn'].apply(fixPrecip) temperature_fahrenheit = stationWeather[u'Mean TemperatureF'] temperature_celcius = (temperature_fahrenheit - 32.) / 1.8 precipitation_mm = 25.4 * precipitation_inch ## in millimeters #sfPrecipitation.max() #[sfPrecipitation != 0.0] #sfTemp.head return (precipitation_mm, temperature_celcius)
def validZip(self,zip): search = ZipcodeSearchEngine() zipcode = search.by_zipcode(zip) if zipcode['Zipcode'] is not None: self.calculatepressure(zipcode=zipcode['Zipcode']) else: print('Please enter a valid zip code')
def init_randomzips(): while True: try: print( 'Please enter the zip code you would like to find accounts around' ) searchzip = int(input('---> ')) print( 'Please enter the radius you would like to find accounts with') searchradius = int(input('---> ')) search = ZipcodeSearchEngine() zipcode = search.by_zipcode(str(searchzip)) mylat = re.findall('"Latitude": (\S+),', str(zipcode)) mylong = re.findall('"Longitude": (\S+),', str(zipcode)) res = search.by_coordinate(zipcode.Latitude, zipcode.Longitude, radius=searchradius, returns=100) searchresults = [] for zipcode in res: searchresults.append(zipcode.Zipcode) searchcity = zipcode.City searchstate = zipcode.State except: print("Sorry, I didn't understand that.") continue else: break print(searchresults)
def get_k_nearest_zipcodes_locations(self, ip_zipcode, radius=50, k_neigh=20): """ Find the zipcodes near to the provided zipcodes. """ search = ZipcodeSearchEngine() lat_long_inf = search.by_zipcode(str(ip_zipcode)) lat, longi = lat_long_inf["Latitude"], lat_long_inf["Longitude"] try: result = search.by_coordinate(lat, longi, radius=radius, returns=k_neigh) except: return None if len(result) == 0: return None else: nearest_zip_list = [] for res in result: nearest_zip_list.append(int(res["Zipcode"])) # Check which all zipcodes are present in the given data. avl_zipcode = set(nearest_zip_list) & set(self._zip_code_list) if avl_zipcode is not None: zip_index_list = [] for code in avl_zipcode: zip_index_list.append(self._zip_code_list.index(code)) return zip_index_list else: return None
def create_user_params(self): """Hold data about the user. We've collected all of the information we need from the user. The last thing that needs to be done is to find out what state they live in, and which district they are from. Then we can find their Presenent reps from that info.""" search = ZipcodeSearchEngine() zipcode = search.by_zipcode(str(self.zip_code)) df = pd.DataFrame(columns=[['email', 'password', 'first_name', 'last_name', 'gender', 'dob', 'street', 'zip_code', 'city', 'state_short', 'state_long', 'district']]) df.loc[0, 'email'] = self.email df.loc[0, 'password'] = user_info.hash_password(self) df.loc[0, 'first_name'] = self.first_name.lower().title() df.loc[0, 'last_name'] = self.last_name.lower().title() df.loc[0, 'gender'] = self.gender.lower().title() df.loc[0, 'dob'] = pd.to_datetime(self.dob) df.loc[0, 'street'] = self.street.lower().title() df.loc[0, 'zip_code'] = str(self.zip_code) df.loc[0, 'city'] = str(zipcode['City'].lower().title()) df.loc[0, 'state_short'] = str(zipcode['State']) df.loc[0, 'state_long'] = str(us.states.lookup(df.loc[0, 'state_short'])) df.loc[0, 'district'] = user_info.get_district_from_address(self, df.loc[0, 'city'], df.loc[0, 'state_short'], df.loc[0, 'state_long']) return df
def zipToCoord(zipCode): """ take zip code and convert them to a zip code :param zipCode: :return: """ search = ZipcodeSearchEngine() results = search.by_zipcode(zipCode) return results
def addusertodatabase(): ########## GET ACCOUNT ########## while True: try: print( 'Please enter your account name as it appears in the URL after "https://soundcloud.com/" ' ) accname = str(input('acc---> ')) url = str("https://soundcloud.com/" + accname) request = requests.get(url) if request.status_code == 200: #makes sure that the soundcloud account name is real by checking the url link to see if it exists/opens break else: print( '\nSorry, this was an invalid response, please try again. Souncloud URL names must only use numbers, lowercase letters, underscores or hyphens, and they must start with a letter or number. \nPlease try again. And make sure you are connected to the internet.' ) continue except: print( '\nSorry, this was an invalid response, please try again. Souncloud URL names must only use numbers, lowercase letters, underscores or hyphens, and they must start with a letter or number. \nPlease try again. And make sure you are connected to the internet.' ) continue else: break readyaccname = accname readyfullurl = url ########## GET ZIP CODE ########## print( 'Please enter the permanent zip code you would like to associate with your account' ) while True: try: acczip = int(getzip()) search = ZipcodeSearchEngine() zipcode = search.by_zipcode(str(acczip)) except ValueError: print( "\nSorry, I didn't understand that. Please enter a valid zip code" ) continue else: break readyacczip = acczip ########## ADD TO DATABASE ########## accounts = {} accounts[readyacczip] = readyaccname with open('accounts.json', 'a') as fp: #opens the existing file, rather than creating a new one json.dump(accounts, fp, indent=4) #adds the individual account zip and name in an organized format print( '\nThank you, your account has been added as \"' + readyaccname + '\" (Full URL:', readyfullurl + ")", 'with Zip Code', readyacczip) options()
def findCityState(zipcode): search = ZipcodeSearchEngine() zip = search.by_zipcode(zipcode) city = zip.City state = zip.State return (city,state)
def extract_location(s): states = utils.states z_search = ZipcodeSearchEngine() possible_locations = find_possible_locations(s) keys = ['State', 'City', 'Zipcode'] for state, zipcode in possible_locations: zip_info = z_search.by_zipcode(zipcode) if states[state] == zip_info['State']: return {key: zip_info[key] for key in keys} return {'State': None, 'City': None, 'Zipcode': None}
def create_zipcode_df(hp_dict): ''' Input: Takes in dictionary of high-prescribing physicians with 'npi' as keys and 'zip' as a value Output: Returns dataframe of longitudes and latitudes for zipcodes of interest ''' from uszipcode import ZipcodeSearchEngine lats = [] longs = [] zips = [] names = [] npis = [] names_zips = [] densities = [] search = ZipcodeSearchEngine() for npi in hp_dict: lats.append(search.by_zipcode(hp_dict[npi]['zip']).Latitude) longs.append(search.by_zipcode(hp_dict[npi]['zip']).Longitude) zips.append(hp_dict[npi]['zip']) npis.append(npi) names.append(hp_dict[npi]['last_name'] + ', ' + hp_dict[npi]['first_name']) names_zips.append(hp_dict[npi]['last_name'] + ', ' + hp_dict[npi]['first_name'] + ', ' + str(hp_dict[npi]['zip'])) densities.append(search.by_zipcode(hp_dict[npi]['zip']).Density) zipcode_df = pd.DataFrame({ 'npi': npis, 'name': names, 'zip': zips, 'name_zip': names_zips, 'latitude': lats, 'longitude': longs, 'density': densities }) zipcode_df['rural'] = 0 zipcode_df.loc[zipcode_df['density'] <= 1000.0, 'rural'] = 1 return zipcode_df
def zipcode_to_latlong(zipcode): """ Takes in zipcode and returns the corresponding latitude and longitude :param zipcode: String or Int of zipcode (either work) :return: Latutude, longitude """ # TODO: this works for some zip codes but not all # (pasadena doesn't work, but LA does). Fix to make it work # for everything search = ZipcodeSearchEngine() loc_data = search.by_zipcode(zipcode) return loc_data['Latitude'], loc_data['Longitude']
def init_addusertodatabase(): ########## GET ACCOUNT ########## x = 0 while x < 300: while True: try: accname = random.choice(randomusers) url = str("https://soundcloud.com/" + accname) request = requests.get(url) if request.status_code == 200: #print(accname) break else: print( '\nSorry, this was an invalid response, please try again. Souncloud URL names must only use numbers, lowercase letters, underscores or hyphens, and they must start with a letter or number. \nPlease try again. And make sure you are connected to the internet.' ) continue except: print( '\nSorry, this was an invalid response, please try again. Souncloud URL names must only use numbers, lowercase letters, underscores or hyphens, and they must start with a letter or number. \nPlease try again. And make sure you are connected to the internet.' ) continue else: break readyaccname = accname readyfullurl = url ########## GET ZIP CODE ########## while True: try: #acczip = random.choice(morezips) acczip = random.choice(randomzips) search = ZipcodeSearchEngine() zipcode = search.by_zipcode(str(acczip)) except ValueError: print( "Sorry, I didn't understand that. Please enter a valid zip code" ) continue else: break readyacczip = acczip ########## ADD TO DATABASE ########## accounts = {} accounts[readyacczip] = readyaccname with open('accounts.json', 'a') as fp: json.dump(accounts, fp, indent=4) print( '\nThank you, your account has been added as \"' + readyaccname + '\"', 'with Zip Code', readyacczip, '\n ') #options() x += 1
def process_form_data(form_list, request): #ImageFormSet = modelformset_factory(Images,form=ImagesForm, extra=3) if request.method == 'POST': form_data = [form.cleaned_data for form in form_list] form = Posting_Form_Final() instance = form.save(commit=False) instance.user = request.user instance.title = form_data[0]['title'] instance.image = form_data[0]['image'] instance.condition = form_data[1]['condition'] instance.description = form_data[1]['description'] instance.price = form_data[2]['price'] instance.email = form_data[2]['email'] instance.phone_number = form_data[2]['phone_number'] instance.street = form_data[3]['street'] instance.city = form_data[3]['city'] instance.state = form_data[3]['state'] instance.zipcode = form_data[3]['zipcode'] instance.height_field = 100 instance.width_field = 100 search = ZipcodeSearchEngine() zipcode = search.by_zipcode(instance.zipcode) instance.longitude = zipcode['Longitude'] instance.latitude = zipcode['Latitude'] instance.save() #Save images (multiple possible) per form #images_form_instance.post = instance #images_form_instance.image images_form = ImagesForm(request.POST, request.FILES) if images_form.is_valid(): photo = images_form.save() data = {'is_valid': True, 'name': photo.image.name, 'url': photo.image.url} else: data = {'is_valid': False} """ import pdb; pdb.set_trace() formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none()) if formset.is_valid() and form.is_valid(): for form in formset.cleaned_data: image = form['image'] photo = Images(post=instance, image=image) photo.save() messages.success(request,"Yeeew, check it out on the home page!") else: print(formset.errors, form.errors) formset = ImageFormSet(queryset=Images.objects.none()) """ return form_list
def get_nearest_zips(zip_code, radius=20): "Return a list of nearest zip codes" nearest_zip_codes = [] search = ZipcodeSearchEngine() my_zip = search.by_zipcode(zip_code) if my_zip['Latitude'] is not None and my_zip['Longitude'] is not None: results = search.by_coordinate(my_zip['Latitude'], my_zip['Longitude'], radius=radius, returns=200) for result in results: nearest_zip_codes.append(result['Zipcode']) return nearest_zip_codes
def get_ratings_for_business_zipcode(business_type, zipcode): """ """ # Get all zipcodes avl in the result. global FINAL_RATINGS_DF FINAL_RATINGS_DF = read_csv_data_to_df(TRAINING_PRED_FILENAME) print len(FINAL_RATINGS_DF) zipcode_list = np.array(FINAL_RATINGS_DF.zipcode).tolist() if zipcode in zipcode_list: rating_row = FINAL_RATINGS_DF[FINAL_RATINGS_DF['zipcode'] == zipcode] rating = rating_row[business_type].tolist()[0] print("Predicted Rating for business: %s, zipcode: %d is %f" % (business_type, zipcode, rating)) return rating else: search = ZipcodeSearchEngine() lat_long_inf = search.by_zipcode(str(zipcode)) lat, longi = lat_long_inf["Latitude"], lat_long_inf["Longitude"] try: result = search.by_coordinate(lat, longi, radius=radius, returns=k_neigh) except: return None if len(result) == 0: return None else: nearest_zip_list = [] for res in result: nearest_zip_list.append(int(res["Zipcode"])) # Check which all zipcodes are present in the given data. avl_zipcode = set(nearest_zip_list) & set(self._zip_code_list) if avl_zipcode is not None: avl_zipcode_list = list(avl_zipcode) ratings = FINAL_RATINGS_DF[FINAL_RATINGS_DF['zipcode'].isin( avl_zipcode_list)] # Calculate avg rating. rating = 0 for row in ratings.iterrows(): rating += ratings[business_type].tolist()[0] avg_rating = rating / len(ratings) print("Predicted Rating for business: %s, zipcode: %d is %f" % (business_type, zipcode, avg_rating)) else: return None
def zip_state(df, zip_col, state_col): ''' :param df: :param zip_col: :param state_col: :return: ''' search = ZipcodeSearchEngine() f = lambda x: str(search.by_zipcode(str(x)).__dict__.get('State')).upper() df[state_col] = df[zip_col].map(f) return df
def get_lat_long(zipcode): """Retrieve Latitude and Longitude from the zip code (US only). Needed to query Dark Sky API Args: zipcode (INT): five-digits zip code Returns: STR: "Lat,Long" """ search = ZipcodeSearchEngine() zipcode = search.by_zipcode(str(zipcode)) return str(zipcode.Latitude) + "," + str(zipcode.Longitude)
def lookup_zipcode_object(zipcode): """ Utility function to lookup a uszipcode zipcode object based on a zipcode string. :param zipcode: Type: String Default: None A string value for a zipcode to lookup :return: If matching zipcode is found a dictionary object for the zipcode including information about it is returned. This is a uszipcode zipcode object. If no zipcode is found, None is returned. """ zipcode_search = ZipcodeSearchEngine() zipcode = zipcode_search.by_zipcode(zipcode) return zipcode
def extract_location(s): z_search = ZipcodeSearchEngine() possible_locations = find_possible_locations(s) keys = ['State', 'City', 'Zipcode'] for state, zipcode in possible_locations: zip_info = z_search.by_zipcode(zipcode) if states[state] == zip_info['State']: d = {key: zip_info[key] for key in keys} d["Confidence_location"] = "high" return d if possible_locations != []: return {'State': possible_locations[0][0], 'City': None, 'Zipcode': possible_locations[0][1], 'Confidence_location': "low"} else: # return {'State': None, # 'City': None, # 'Zipcode': None, # 'Confidence_location': None} return None
def getZipCodeUsersJson(): data = [] listZCode = [] jsonArray = [] zcode = dfusers.groupBy("Zip-code").count().collect() search = ZipcodeSearchEngine() for code in zcode: jsonObjet = {} jsonObjet['zip'] = code[0] zipcode = search.by_zipcode(code[0]) listZCode.append(zipcode["City"]) jsonObjet['country'] = zipcode["City"] jsonObjet['name'] = zipcode["State"] jsonObjet['z'] = code[1] jsonObjet['y'] = code[1] data.append(jsonObjet) jO = {} jO['data'] = data jO['categoris'] = listZCode jsonArray.append(jO) return json.dumps(jsonArray)
def editBio(request): if not request.user.is_authenticated: return redirect('/accounts/login') current_user = request.user e_user = ExtendedUser.objects.get(user=current_user) try: a_user = get_object_or_404(AdminUser, extended_user=e_user) except: return redirect('/home') if a_user.registered is not True: return redirect('/home') if request.method == 'POST': e_user = ExtendedUser.objects.get(user=current_user) form = BioForm(request.POST, request.FILES, instance=e_user) if form.is_valid(): e_user.bio = form.cleaned_data['bio'] e_user.first = True zipcode_in = form.cleaned_data['zipcode'] e_user.zipcode = zipcode_in search = ZipcodeSearchEngine() zipcode = search.by_zipcode(str(zipcode_in)) # type: object print(zipcode['City'] == None) if (zipcode['City'] == None): return render(request, "bio.html", { 'form': form, 'instance': e_user, 'error': 'invalidzipcode' }) e_user.city = zipcode['City'] e_user.state = zipcode['State'] e_user.photos = form.cleaned_data['photos'] e_user.save(force_update=True) message_type = True message = "User update successfully." request.session['message'] = message request.session['message_type'] = message_type return redirect('/userinfo') elif request.method == 'GET': form = BioForm(instance=e_user) return render(request, "bio.html", {'form': form, 'instance': e_user})
def addUserAddress(user, description = "", name = "", address_line1 = "", address_line2 = "", address_city = "" ,address_state = "", address_zip = "", address_country = "US"): # we don't do international right now if address_country != "US": raise Exception("Address must be in US") search = ZipcodeSearchEngine() zipcode = search.by_zipcode(address_zip) if zipcode[State] != address_state: raise Exception("ZIP Code and State do not match") try: verification = Lob.verifyAddress(name, address_line1, address_line2, address_city, address_state, address_zip, address_country) if verification[DELIVERABILITY] in ERROR_DELIVERABLE: raise Exception("Error, we cannot deliver to this address. \ Please check your information and try again.") address = lob.Address.create( description= description, name= name, company='Lob', address_line1= address_line1, address_line2= address_line2, address_city= address_city, address_state = address_state, address_zip = address_zip, address_country= address_country, metadata = { AccountId : user.account_id } ) return address except Exception as e: raise Exception("Error adding address : " + str(e))
def parser(location): ''' Parse the json for needed data''' # We are given an string of the zip. # to use the api, we need to change it to lat/lon search = ZipcodeSearchEngine() curZipcode = search.by_zipcode(location) # print(curZipcode) if curZipcode['City'] is None: return 'ERROR' lat = curZipcode['Latitude'] lon = curZipcode['Longitude'] # API url url = 'https://api.darksky.net/forecast/73e7ea4a962e1d8c65470b15ceda0965/' url = url + str(lat) + ',' + str(lon) # Calling the API and parsing it weather = get(url) if 'error' in weather: return 'ERROR' totalHourlyInfo = weather['hourly'] hourlyData = totalHourlyInfo['data'] # This is the relevent hourly data for the current location data = [] for curHourData in hourlyData: # (time, apparentTemp, summary) # time is in unix timestamp, second counting from 1970 1/1 # Summary is the condition condition = curHourData['icon'] time = curHourData['time'] apparentTemp = curHourData['apparentTemperature'] uvIndex = curHourData['uvIndex'] data.append((datetime.datetime.fromtimestamp(time), apparentTemp, condition, uvIndex, curZipcode['City'])) return data
def get_rich_zipcode(self) -> Optional[Zipcode]: if not self.zipcode: return None search = ZipcodeSearchEngine() return search.by_zipcode(self.zipcode)
def convert_zip_to_region(zipcode): state_region_dct = {'AK': 'West', 'AL': 'South', 'AR': 'South', 'AZ': 'West', 'CA': 'West', 'CO': 'West', 'CT': 'Northeast', 'DC': 'South', 'DE': 'South', 'FL': 'South', 'GA': 'South', 'HI': 'West', 'IA': 'Midwest', 'ID': 'West', 'IL': 'Midwest', 'IN': 'Midwest', 'KS': 'Midwest', 'KY': 'South', 'LA': 'South', 'MA': 'Northeast', 'MD': 'South', 'ME': 'Northeast', 'MI': 'Midwest', 'MN': 'Midwest', 'MO': 'Midwest', 'MS': 'South', 'MT': 'West', 'NC': 'South', 'ND': 'Midwest', 'NE': 'Midwest', 'NH': 'Northeast', 'NJ': 'Northeast', 'NM': 'West', 'NV': 'West', 'NY': 'Northeast', 'None': 'West', 'OH': 'Midwest', 'OK': 'South', 'OR': 'West', 'PA': 'Northeast', 'PR': 'Other', 'RI': 'Northeast', 'SC': 'South', 'SD': 'Midwest', 'TN': 'South', 'TX': 'South', 'UT': 'West', 'VA': 'South', 'VT': 'Northeast', 'WA': 'West', 'WI': 'Midwest', 'WV': 'South', 'WY': 'West'} search = ZipcodeSearchEngine() zipcode = search.by_zipcode(zipcode) state = zipcode.State if state is not None: region = state_region_dct[state] return region