Remove python 3 phrase

I have a list of strings that I would like to find in the phrase. Then delete the list if the combination does not exist. Is there a python list understanding that will work?

word_list = ["Dogs love ice cream", "Cats love balls", "Ice cream", "ice cream is good with pizza", "cats hate ice cream"] keep_words = ["Dogs", "Cats"] Delete_word = ["ice cream"] 

Remove the words that contain ice cream, but if dogs or cats are in the sentence, keep it.

 Desired_output = ["Dogs love ice cream", "Cats love balls", "cats hate ice cream"] 

I tried this code and tried to use AND and OR, but could not get the combination correctly.

 output_list = [x for x in word_list if "ice cream" not in x] 
+5
source share
3 answers

Here is a list comprehension solution:

 [x for x in word_list if any(kw.lower() in x.lower() for kw in keep_words) or all(dw.lower() not in x.lower() for dw in Delete_word)] # ['Dogs love ice cream', 'Cats love balls', 'cats hate ice cream'] 

It also adds flexibility to multiple words in the delete word list.

Explanation

Scroll through the list and save the word if one of the following values: True :

  • Any of keep words is in x
  • None of the words delete in x

I assume from your example that you want this to be case insensitive, so do all the comparison with the versions of the words with the bottom box.

Two useful functions: any() and all() .

+6
source

As an optimized approach, you can set keep_word and delete_words inside the set and use itertools.filterfalse() to filter the list:

 In [48]: def key(x): words = x.lower().split() return keep_words.isdisjoint(words) or not delete_words.isdisjoint(words) ....: In [49]: keep_words = {"dogs", "cats"} In [51]: delete_words = {"ice cream"} In [52]: list(filterfalse(key ,word_list)) Out[52]: ['Dogs love ice cream', 'Cats love balls', 'cats hate ice cream'] 
+5
source
 >>> list(filter(lambda x: not any(i in x for i in Delete_word) ... or any(i in x for i in keep_words), word_list)) ['Dogs love ice cream', 'Cats love balls', 'Ice cream'] 

Change this to a case insensitive implementation.

+1
source

Source: https://habr.com/ru/post/1275203/


All Articles