How to match string and return the word with closest match

Viewed 26

I am trying to look for a keyword in a sentence and return the whole word. For example my keyword is 'str' and if there's match for 'str' in all_text, I want to return 'string' .

all_text = 'some rather long string'
keyword_list = ['str', 'rat', 'me', 'ng']


for item in keyword_list:
      if item in all_text:
            print(item)

str
rat
me
ng

Instead of str, rat, me , ng I want to return string, rather, some, long.

2 Answers

Here are a couple of ways you can do this. Firstly you can just split the sentence into words and see if the text is contained in them:

all_text = 'some rather long string'
keyword_list = ['str', 'rat', 'me', 'ng']

words = [word for word in all_text.split() if any(key in word for key in keyword_list)]

Alternatively you can build a regex which will match the word surrounding the keyword:

import re

regex = re.compile(fr'\b\w*(?:{"|".join(keyword_list)})\w*\b')
words = re.findall(regex, all_text)

In both cases the output is

['some', 'rather', 'long', 'string']

here is one way to do it, using python and not pandas

import re

#create an OR statement with all the keywords
s='|'.join(keyword_list)

# split the sentence at space, and iterate through it
for w in all_text.split(' '):

# check if word is in the search-words-list
    if (len(re.findall(s, w, re.IGNORECASE) ) >0) :

# print when found
        print (w)

some
rather
long
string
Related