sourmango
sourmango

Reputation: 19

Find the first match from a list of words in a string

I am writing a function that finds a keyword in a string and returns the first match, if any.

The keywords are "what", "when", "who"

Example:

Is there a way to compare a list of keywords against a string input and return the first match?

I thought about using re.search but it takes single string at a time. This is what I have so far:

question = input("Ask me a question: ")
 keywords = ("what", "when", "who")
 question = question.lower()
 match = re.search(r'word:', question) #  re.search seems to take only one string at a time

Upvotes: 1

Views: 1209

Answers (4)

Antimon
Antimon

Reputation: 702

Split the input into words and compare each against your set of keywords; break from the loop if a match is found, or return if you want to wrap it into a function.

for word in question.split():
    if word in keywords:
        match = word
        break

Also, take care to handle cases when no match is found.

Upvotes: 0

oppressionslayer
oppressionslayer

Reputation: 7204

This will find the fist word in the list and give you the location of it:

question = input("Ask me a question: ")
keywords = ("what", "when", "who")
question = question.lower()

for keyword in keywords:
   loc = question.find(keyword)
   if loc == -1:
      loc = "Not Found"
   else:
       print('{} was found at location: {} and is the first match found in the list of keywords'.format(keyword, loc))
       break

Upvotes: 0

Barmar
Barmar

Reputation: 780673

Convert your list to a regular expression of the form \b(?:what|when|who)\b, then use re.search().

question = input("Ask me a question: ").lower()
keywords = ("what", "when", "who")
kw_re = r'\b(?:' + '|'.join(map(re.escape, keywords)) + r')\b'
match = re.search(kw_re, question)

\b matches word boundaries, so this will only match whole words.

Upvotes: 2

Alexander
Alexander

Reputation: 109510

Testing a word for inclusion in a set of keywords is O(1) vs. O(n) for a list of n keywords.

def find_match(sentence, keyword_set):
    for word in sentence.split():
        if word in keyword_set:
            return word

keywords = {"what", "when", "who"}
question = "Who is John Connor".lower()
>>> find_match(question, keywords)
'who'

Upvotes: 1

Related Questions