Created
June 7, 2013 17:35
-
-
Save catalan42/5730957 to your computer and use it in GitHub Desktop.
A simple demo to count all the space-delimited words in a file. Usage: counter <filename>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment