Reputation: 15
I have a dictionary of self-input locations and a list of possible locations from geonamescache. For example, a self-input user location could be "san bernadino ca" and the list of all locations contains both "san bernadino" and "ca." I am trying to figure out how to split the string "san bernadino ca" into ["san bernadino", "ca"] based on the second dictionary. This is in Python.
What I have tried:
Let user_locations be a list of self-input user locations.
Let locations be a dict of real location names/keys (like "california", "ca", and "san bernadino")
for user_location in user_locations
for location in locations.keys():
if location in user_location:
print(location, user_location)
But, this prints results like "ar san bernardino ca" even though it's clear the user location is not Arkansas, but AR is the code for Arkansas. My instinct was to split the place names into a list since in just checks characters and not words, but split() separates san and bernadino even though I want them together.
Any help would be appreciated!
Upvotes: 0
Views: 53
Reputation: 23099
The code you show seems like a valid idea to me. Since I don't know what your input data structures look like, it's hard to know what you're getting and what you want the behavior to be instead.
One thing...the way you're using print
will make it hard to know what you're getting. The two values you are printing will be spliced together with no delimiters.
Since your solution seemed close to something that would work, I grabbed it and put a solution together that it seems gives you what you're looking for. Here's what I came up with:
user_locations = [
"It's too hot in san bernadino, ca !!!",
"my name is Joe. I'm from Portland, Oregon, and I like apples"
]
locations = {"san bernadino": "", "ca": "", "Portland": "", "Oregon": ""}
for user_location in user_locations:
result = []
for location in locations.keys():
if location in user_location:
# print(f'"{location}" found in "{user_location}"')
result.append(location)
print(f"Result: {result}")
Result:
Result: ['san bernadino', 'ca']
Result: ['Portland', 'Oregon']
I went with a dictionary for locations
so that I didn't have to change your use of location.keys()
. If you don't need to associate values with the found words, you could remove the :""
from each entry in locations
, in which case you'd have a set
, and you could remove the .keys()
when referencing that structure.
Upvotes: 1