Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a sentence contains two or more words from my list

Tags:

python

list

Thanks for the quick and great help everytime i post questions here!:)

Hope all you have great days!

My questions is how can i check whether a sentence contains two or more words from my list

For example

mylist = ['apple', 'banana', 'monkey', 'love']

Sentence1 = "Monkeys love bananas"

-> as monkey, love, banana those three words are in list I want to get this sentence 1 as positive

Sentence2 = "The dog loves cats"

-> since sentence2 only contains the word "love" from my list, I want to get this sentence2 as negative

I learned that in case of checking whether a sentence contains any single word in list, I could use

if any (e in text for e in wordset):

However, i could not find the solution that could deal with the problem stated above.

Could anyone give help?

(As there are bunch of sentences that are not using English, It would be very hard to use NLP tools, such as stemming or lemmantizing)

like image 394
ChanKim Avatar asked Jan 31 '26 05:01

ChanKim


1 Answers

You need to iterate through your mylist and check if the word in mylist is present in your sentence. If present put that into a list and find the length. If the length is >= 2 then positive!

>>> mylist = ['apple', 'banana', 'monkey', 'love']
>>> s1 = "Monkeys love bananas"    
>>> len([each for each in mylist if each.lower() in s1.lower()])>=2
True
>>> s2="The dog loves cats"
>>> len([each for each in mylist if each.lower() in s2.lower()])>=2
False

The same using lambda,

>>> checkPresence = lambda mylist,s : len([each for each in mylist if each.lower() in s.lower()])>=2
>>> checkPresence(mylist,s1)
True
>>> checkPresence(mylist,s2)
False
like image 167
Keerthana Prabhakaran Avatar answered Feb 02 '26 17:02

Keerthana Prabhakaran