Message Boards Message Boards

0
|
1222 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

How can I find sentences that contain this but not that?

Posted 8 months ago

Hello everyone,

I want to pick sentences that contain one substring but not another from a long list of sentences. I've done this by applying StringContainsQ for the substring I want and Not[StringContainsQ] separately for the substring I do not want, and then mapping And across the result. Here's an example with a list of three sentences. The code picks the ones that contain "cat" but not "rat".

sentences = {"The rat avoids the cat.", "The cat wears a hat.", 
  "The dog days of summer have past."}

Map[#[[1]] && #[[2]] &,
 Transpose[
  {
   StringContainsQ[sentences, WordBoundary ~~ "cat" ~~ WordBoundary, 
    IgnoreCase -> True],
   Not/@StringContainsQ[sentences, WordBoundary ~~ "rat" ~~ WordBoundary, 
     IgnoreCase -> True]
   }
  ]
 ]

Pick[sentences, %]

It works fine, but I was wondering if there is a slicker way to do it.

Greg

POSTED BY: Gregory Lypny
2 Replies
Posted 8 months ago

Good stuff! Thank you, Eric.

POSTED BY: Gregory Lypny
Posted 8 months ago
Select[
 sentences, 
 And[StringContainsQ[WordBoundary ~~ "cat" ~~ WordBoundary][#], 
   StringFreeQ[WordBoundary ~~ "rat" ~~ WordBoundary][#]] &]
POSTED BY: Eric Rimbey
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract