shamant
shamant

Reputation: 57

Matching words in a string that appear together

I'm trying to match words in a string that appear together, irrespective of their order of appearance.

I've tried doing something really basic. It gives me the expected result but I have to match any number of words entered by the user.

Example: user wants to match "great product"

str="great product. affordable useful cool."
if (str.find("great product")) != -1 or (str.find("product great")) != -1:
       print(str)

Gives expected result. Now, if user wants to check if the string has the words

"useful affordable cool"

in any order as long as they appear together.

str has those words and so, it must match.

How would I do that? Should I use regex?

Any help would be greatly appreciated. Thanks!

Upvotes: 2

Views: 89

Answers (2)

Rakesh
Rakesh

Reputation: 82765

Using itertools.permutations and any

Ex:

tolook = "useful affordable cool".split()
str_val = "great product. affordable useful cool."
if any(i in str_val for i in [" ".join(comb) for comb in permutations(tolook, len(tolook))]):
    print("Found")
else:
    print("N\A")

#--->Found

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

If you wanted to handle this via a single regex, you could try using this pattern:

^(?=.*\buseful\b)(?=.*\baffordable\b)(?=.*\bcool\b).*$

Python script:

input = "great product. affordable useful cool."
match = re.match(r'^(?=.*\buseful\b)(?=.*\baffordable\b)(?=.*\bcool\b).*$', input)
if match:
    print("MATCH")

The regex pattern above makes use of positive lookaheads, each of which asserts that one of the keywords appears in the input string. For example:

(?=.*\buseful\b)

asserts that useful appears. The combination of the three lookaheads covers all three keywords.

Upvotes: 4

Related Questions