Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

2 Answers 2

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 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

 
discard

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.