Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 7 down vote accepted

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 *)
share|improve this answer
Could you explain why you don – Daniel Mar 17 '14 at 5:40

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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