Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Match the beginning of a state's name as well as its verbose name #77

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions us/states.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ def shapefile_urls(self) -> Optional[Dict[str, str]]:
return urls


def lookup(val, field: Optional[str] = None, use_cache: bool = True) -> Optional[State]:
"""Semi-fuzzy state lookup. This method will make a best effort
def lookup(val, field: Optional[str] = None, use_cache: bool = True, deep_lookup: bool = False) -> Optional[State]:
"""Semi-fuzzy state lookup. This method will make the best effort
attempt at finding the state based on the lookup value provided.

* two digits will search for FIPS code
Expand Down Expand Up @@ -105,6 +105,19 @@ def lookup(val, field: Optional[str] = None, use_cache: bool = True) -> Optional
if use_cache:
_lookup_cache[cache_key] = state

if not matched_state and deep_lookup:
val = " ".join(
val.rstrip(".")
.lower()
.replace("state", "").replace(" of ", "").replace("a ", "").replace("the ", "")
.split()
)
for state in STATES_AND_TERRITORIES:
if state.name.lower().startswith(val):
matched_state = state
if use_cache:
_lookup_cache[cache_key] = state

return matched_state


Expand Down
8 changes: 8 additions & 0 deletions us/tests/test_us.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,14 @@ def test_obsolete_lookup():
assert us.states.lookup(state.name) is None


def test_deep_lookup():
assert us.states.lookup("Cal.", field="name", deep_lookup=True) == us.states.CA
assert us.states.lookup(" Mary ", field="name", deep_lookup=True) == us.states.MD
assert us.states.lookup("The New York State ", field="name", deep_lookup=True) == us.states.NY
assert us.states.lookup(" a State of Washington", field="name", deep_lookup=True) == us.states.WA
assert us.states.lookup("State of the Washington", field="name", deep_lookup=True) == us.states.WA


# test metaphone


Expand Down