5
$\begingroup$

My question is about StringCases. When I use this function, each word is separated by a ,. But I want some noun phrases like names of a ministry to be considered single words.

For example, I would like to count the number of words in the next two sentences.

text= "The Ministry of Infrastructure and Environment is 
committed to improving quality of life,access and mobility in a 
clean,safe and sustainable environment.The Ministry strives to create 
an efficient network of roads,railways,waterways and 
airways,effective water management to protect against flooding,and 
improved air and water quality"

StringCases[text, WordCharacter ..]

The result of this function is:

{"The", "Ministry", "of", "Infrastructure", "and", "Environment", 
"is", "committed", "to", "improving", "quality", "of", "life", 
"access", "and", "mobility", "in", "a", "clean", "safe", "and", 
"sustainable", "environment", "The", "Ministry", "strives", "to", 
"create", "an", "efficient", "network", "of", "roads", "railways", 
"waterways", "and", "airways", "effective", "water", "management", 
"to", "protect", "against", "flooding", "and", "improved", "air", 
"and", "water", "quality"}

Each word is separated by a ','. When I count the number of words I get 50, but there are four noun phrases I want to be considered single words:

"Ministry of Infrastructure and Environment"
"quality of life"
"network of roads"
"water management"

So the word count I would like to get is 41. I can create a reference table with all possible combinations of words. Is there a solution for this problem?

$\endgroup$
7
$\begingroup$

You could add the "special" word combinations to the pattern using Alternatives:

specials = Sequence[
  "Ministry of Infrastructure and Environment",
  "quality of life",
  "network of roads",
  "water management"]

StringCases[text, specials | WordCharacter ..] // Length

(* 41 *)
$\endgroup$
  • $\begingroup$ Could you explain why you don $\endgroup$ – Daniel Mar 17 '14 at 5:40
4
$\begingroup$

If you just want the count, short & sweet:

StringCount[text, {"Ministry of Infrastructure and Environment", 
  "quality of life", "network of roads", "water management", WordCharacter ..}]

Same form but with StringCases gives you the actual "words", with special cases treated as such.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.