BookmarkSubscribeRSS Feed
shivamnegi92
Calcite | Level 5

 

I'm looking to create a column that contains the word 3 words before and 3 words directly after a keyword in my target column "Apple Description"

 

For example, if the keyword I would like to search for is "Apple" then

The market has apples and alot of bananas  ==>  column 1 ->> "The market has" .  column 2 ->> " and alot of "

I love to eat a lot of apples ==> "a lot of"

I like orange juice ==>  ""

 

And I would like to apply that to multiple keywords like "apple" or "apple like" or "apple fruit" altogether.

 

Thanks!

 

CF

 

 

data want;
  length before after $200;
  string="a b c d e trigger f g h i j";
  do i=1 to countw(string," ");
    if scan(string,i," ")="trigger" then do;
      before=scan(string,i-5," ");
      after=scan(string,i+5," ");
      before2=scan(string,i-4," ");
      after2=scan(string,i+4," ");
    end;
  end;
run;

 

2 REPLIES 2
novinosrin
Tourmaline | Level 20
/*fun stuff*/

data want;
string='The market has apples and alot of bananas';
length before after $50;
  do i=1 to countw(string," ");
      if  scan(string,i," ")='apples' then do;
	  do n=i-3 to i-1 ;
	  before=catx(' ',before,scan(string,n));
      end;
	
	  do n=i+1 to i+3;
	  after= catx(' ',after,scan(string,n));
		end;
		end;
	end;
drop n i;
run;
shivamnegi92
Calcite | Level 5

That is very helping. Thanks , that partially solved my problem. Suppose, instead of a string, I have to apply it to a column, how we can go ahead with this code.

 

By that, I mean, suppose instead of string, we have a dataframe with a specific column we are targetting , suppose -- "Apple summary". Then if you wanna find out 3 words before and after a keyword -"Apple", And create 2 columns with --3 WORDS BEFORE "apple" and 3 words after apple, then how you will go ahead.

 

Sorry, I have limited understanding about SAS. 

Thanks again for quick reply.

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

How to choose a machine learning algorithm

Use this tutorial as a handy guide to weigh the pros and cons of these commonly used machine learning algorithms.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 2 replies
  • 1385 views
  • 1 like
  • 2 in conversation