santiagomarind
santiagomarind

Reputation: 3

Find matching words from a list in a string, return the matching word(s) - Py

I am writing a code to check if the words of a string match with a list of words. I already have the following function that works perfectly:

def lookup(string,list_of_words):
     if any(i in string for i in list_of_words)==True:
        return 1
     else:
        return 0

However, now I want the function not to return 0's or 1's, but the word that matches, ej:

list_of_words=['pencil','eraser','marker']
lookup2('I have a pencil and a pen', list_of_words)
#output: 
'pencil'

I wrote the following code but it returns the error NameError: name 'i' is not defined:

def lookup2(string,list_of_words):
    if any(i in string for i in words)==True:
        return i
    else:
        return np.nan

Do you guys know how can I make it work properly? Thank you

Upvotes: 0

Views: 2490

Answers (4)

Woodford
Woodford

Reputation: 4439

Another variation:

>>> list_of_words = ['pencil', 'eraser', 'marker']
>>> sentence = 'I have a pencil and a pen'
>>> [word for word in list_of_words if word in sentence]
['pencil']

Upvotes: 0

DarrylG
DarrylG

Reputation: 17156

Your approach can be made to work by using the Walrus operator available in Python 3.8+.

def lookup2(string, list_of_words):
    if any((p:=i) in string for i in list_of_words):  # ==True not needed
        return p                                      # p value maintained from list comprehension
    else:
        return None                                   # None more standard to return for string matching

Or more succinctly:

def lookup2(string, list_of_words):
    return p if any((p:=i) in string for i in list_of_words) else None

Upvotes: 0

Алексей Р
Алексей Р

Reputation: 7627

def lookup2(string, list_of_words):
    return set(string.split()).intersection(list_of_words)

list_of_words = ['pencil', 'eraser', 'marker']
print(lookup2('pencil eraser', list_of_words))  # {'pencil', 'eraser'}

Upvotes: 1

user15801675
user15801675

Reputation:

You can try this:

def lookup2(string,list_of_words):
    return ','.join(j for j in string.split() if j in list_of_words)

Essentially, what it is doing is:

  1. Iterating over splitted string's elements (.split() method returns a list)
  2. Checking if any word is in list_of_word
  3. Joining it by ,

Upvotes: 2

Related Questions