예제 #1
0
파일: bap.py 프로젝트: soldiers1989/MDCetl
	def create_postal_code_list():
		pcdb = PostalCodeDatabase()
		results = pcdb.get_postalcodes_around_radius('T3Z', 2500)
		print(type(results))
		cl = ['postalcode', 'city', 'province', 'longitude', 'latitude', 'timezone', 'dst']
		dfs = pd.DataFrame(columns=cl)
		for r in results:
			df = pd.DataFrame([r.__dict__], columns=cl)
			dfs = pd.concat([dfs, df])
		dfs
예제 #2
0
def searchlongitude(x):
    #print(x)
    pcdb = PostalCodeDatabase()
    try:
        location = pcdb[x]
        return location.longitude
    except:
        return "Not found"
 def look_up_zip(self, zip, country, formatted=False):
     if country == "US":
         info = self.get_us_search().by_zipcode(zip)
         if formatted:
             info = self.format_place(zip, info.major_city, info.state)
     elif country == "CA":
         info = PostalCodeDatabase()[zip]
         if formatted:
             info = self.format_place(zip, info.city, info.province)
     return info
 def look_up_zip(self, zip, country, formatted=False):
     if country == "US":
         info = uszipcode.SearchEngine(simple_zipcode=True).by_zipcode(zip)
         if formatted:
             info = self.format_place(zip, info.major_city, info.state)
     elif country == "CA":
         info = PostalCodeDatabase()[zip]
         if formatted:
             info = self.format_place(zip, info.city, info.province)
     return info
def count_data(infile):
    pcdb = PostalCodeDatabase(ConnectionManager())

    lookup_errors = []

    with open(infile, "rb") as csv_in:
        reader = csv.DictReader(csv_in, encoding='utf-8')

        i = 1
        for row in reader:
            i += 1
            postal_code = row['Postal Code'].strip().upper()
            forward_sortation_area = postal_code[:3]
            try:
                pcdb[forward_sortation_area]
            except IndexError:
                lookup_errors.append([i, postal_code])

    return lookup_errors
예제 #6
0
country = 'Canada'  # only support canada at this time
# Postcode
postcodes = []
# city
cities = []
# province
provinces = []
# address_id
address_ids = []
# street_num
street_nums = []
# street_name
street_names = []

# get the postcode database
pcdb = PostalCodeDatabase()

for restaurant in restaurants:
    # Postcode
    postcode = restaurant['location']['zip_code']
    try:
        postcode_info = pcdb[postcode[0:3]]
    except IndexError:
        continue
    city = postcode_info.city
    province = postcode_info.province

    # Address
    address = restaurant['location']['address1']
    try:
        address_id = hashlib.sha1(
예제 #7
0
 def __init__(self):
   self.pcdb = PostalCodeDatabase()
예제 #8
0
class postalCodeManager():
    """
        Constructor
    """
    def __init__(self):
        self.pcdb = PostalCodeDatabase()

    """
        Verifies that the provided postal code is valid in Canada

        :param _postalCode: the postal code to be checked
    """

    def verifyPostalCode(self, _postalCode):
        try:
            location = self.pcdb[_postalCode[:3]]
        except:
            return False
        return (_postalCode[3].isnumeric() and _postalCode[4].isalpha()
                and _postalCode[5].isnumeric())

    """
        Gets nearby passcodes for a provided base passcode and radius

        :param _postalCode: Base postal code for searching
        :param radius: Search radius
    """

    def getNearybyPassCodes(self, _passcode, radius):
        pc = _passcode[:3]
        radius = radius
        results = self.pcdb.get_postalcodes_around_radius(pc, radius)
        nearby_postal_codes = set()
        for r in results:
            nearby_postal_codes.add(r.postalcode + '%')
        nearby_postal_codes = list(nearby_postal_codes)
        nearby_postal_codes = tuple(nearby_postal_codes)
        return nearby_postal_codes

    """
        Finds the postal code associated with a city

        :param city: city to be searched for
    """

    def getPCfromCity(self, city):
        city = city.strip()
        all = self.pcdb.find_postalcode()
        for i in all:
            if city.lower() in i.city.lower():
                return i.postalcode
        return None

    """
        Find the city associated with the postal code

        :param _postalCode: target postal code
    """

    def getCityFromPC(self, _postalCode):
        try:
            res = self.pcdb[_postalCode[:3]]
        except:
            return "Vancouver, British Columbia, Canada"
        return f"{res.city}, {res.province}, Canada"
    def validate_geographic_areas(self, values, db):
        # Note: the validator does not recognize data from US territories other than Puerto Rico.

        us_search = self.get_us_search()
        ca_search = PostalCodeDatabase()
        CA_PROVINCES = {
            "AB": "Alberta",
            "BC": "British Columbia",
            "MB": "Manitoba",
            "NB": "New Brunswick",
            "NL": "Newfoundland and Labrador",
            "NT": "Northwest Territories",
            "NS": "Nova Scotia",
            "NU": "Nunavut",
            "ON": "Ontario",
            "PE": "Prince Edward Island",
            "QC": "Quebec",
            "SK": "Saskatchewan",
            "YT": "Yukon Territories",
        }

        locations = {"US": [], "CA": []}

        for value in json.loads(values):
            flagged = False
            if value == "everywhere":
                locations["US"].append(value)
            elif len(value) and isinstance(value, str):
                if len(value) == 2:
                    # Is it a US state or Canadian province abbreviation?
                    if value in CA_PROVINCES:
                        locations["CA"].append(CA_PROVINCES[value])
                    elif len(us_search.query(state=value)):
                        locations["US"].append(value)
                    else:
                        return UNKNOWN_LOCATION.detailed(
                            _(
                                '"%(value)s" is not a valid U.S. state or Canadian province abbreviation.',
                                value=value,
                            )
                        )
                elif value in list(CA_PROVINCES.values()):
                    locations["CA"].append(value)
                elif self.is_zip(value, "CA"):
                    # Is it a Canadian zipcode?
                    try:
                        info = self.look_up_zip(value, "CA")
                        formatted = "%s, %s" % (info.city, info.province)
                        # In some cases--mainly involving very small towns--even if the zip code is valid,
                        # the registry won't recognize the name of the place to which it corresponds.
                        registry_response = self.find_location_through_registry(
                            formatted, db
                        )
                        if registry_response:
                            locations["CA"].append(formatted)
                        else:
                            return UNKNOWN_LOCATION.detailed(
                                _(
                                    'Unable to locate "%(value)s" (%(formatted)s).  Try entering the name of a larger area.',
                                    value=value,
                                    formatted=formatted,
                                )
                            )
                    except:
                        return UNKNOWN_LOCATION.detailed(
                            _(
                                '"%(value)s" is not a valid Canadian zipcode.',
                                value=value,
                            )
                        )
                elif len(value.split(", ")) == 2:
                    # Is it in the format "[city], [state abbreviation]" or "[county], [state abbreviation]"?
                    city_or_county, state = value.split(", ")
                    if us_search.by_city_and_state(city_or_county, state):
                        locations["US"].append(value)
                    elif len(
                        [
                            x
                            for x in us_search.query(state=state, returns=None)
                            if x.county == city_or_county
                        ]
                    ):
                        locations["US"].append(value)
                    else:
                        # Flag this as needing to be checked with the registry
                        flagged = True
                elif self.is_zip(value, "US"):
                    # Is it a US zipcode?
                    info = self.look_up_zip(value, "US")
                    if not info:
                        return UNKNOWN_LOCATION.detailed(
                            _('"%(value)s" is not a valid U.S. zipcode.', value=value)
                        )
                    locations["US"].append(value)
                else:
                    flagged = True

                if flagged:
                    registry_response = self.find_location_through_registry(value, db)
                    if registry_response and isinstance(
                        registry_response, ProblemDetail
                    ):
                        return registry_response
                    elif registry_response:
                        locations[registry_response].append(value)
                    else:
                        return UNKNOWN_LOCATION.detailed(
                            _('Unable to locate "%(value)s".', value=value)
                        )
        return locations