public
Created

A simple demo to count all the space-delimited words in a file. Usage: counter <filename>

  • Download Gist
counter.groovy
Groovy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#!/usr/bin/env groovy
 
// A simple demo to count all the space-delimited words in a file.
// Usage: counter <filename>
class Counter {
// A list of sets. Words of length L are stored in words[L]. All words are
// stored as lowercase.
List<Set> words = []
 
void run( args ) {
if ( args.size() < 1 ) {
println "Usage: counter <filename>"
return
}
File file = new File( args[0] )
 
println ""
println "Loading: " + file.getCanonicalPath()
List fileWords = file.text.tokenize()
int maxLen = fileWords*.size().max()
// Init empty words structure
words = []
for ( int ii in (0 .. maxLen) ) {
words[ii] = new HashSet()
}
 
int totalWords = 0;
fileWords.each { word ->
def wordLen = word.size()
def wordLower = word.toLowerCase()
words[ wordLen ] << wordLower
totalWords++
}
 
println()
words.eachWithIndex { wordSet, idx ->
int numWords = wordSet.size()
println "$idx".padLeft(5) + ": " + "${numWords}".padLeft(7) + " words"
}
}
 
static main(args) {
new Counter().run( args )
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.