Check if word is in proximity of another word

Viewed 36

I am trying to verify if words from a list are in proximity to words from another list. I define proximity as words that are near each other by a range of 5 words.

I tried using the following regular expression, but with little success:

\b(word1|word2|word3)(?:\W+\w+){1,6}?\W+(word1|word2|word3)\b

I was able to use the following code, but only to check the proximity between two words:

import re

text = ("If you want to use the same regular expression more than once, you should compile it into a regular expression object. ")

def search(target, text, context=5):
    words = re.findall(r'\w+', text)

    matches = (i for (i,w) in enumerate(words) if w.lower() == target)
    for index in matches:
        if index < context //2:
            yield words[0:context+1]
        elif index > len(words) - context//2 - 1:
            yield words[-(context+1):]
        else:
            yield words[index - context//2:index + context//2 + 1]

def extract(word):
    return(list(search(word, text)))

def check(word, lst):
    if word in lst:
        print("The word is in the list")
    else:
        print("The word is not in the list")
    
def main(word1, word2, lst):
    extract(word1)
    check(word2, lst)
        
main("expression", "once", text)

My questions are: First, how would you streamline the above code to make it faster on large texts? Second, how would you go ahead to search for combination of multiple words (eg. check if one of ["expression", "banana", "same"] appears in proximity of one of ["once", "split", "use"]?

Thank you for your help.

0 Answers
Related