Hi guys,
today is day 8 out of 100 days of code.
The task for today is to count words frequency reading data from stdin. Input is scanned using bufio *Scanner with a split by words(ScanWords).
Lets see the code:
package main import ( "bufio" "fmt" "os" ) func main() { //map to store words frequency words := make(map[string]int) //we will read from file in := bufio.NewReader(os.Stdin) scanner := bufio.NewScanner(in) //we ask scanner to split input by words for us scanner.Split(bufio.ScanWords) count := 0 //scan the inpurt for scanner.Scan() { //get input token - in our case a word and update it's frequence words[scanner.Text()]++ count++ } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading input:", err) } fmt.Printf("Total words: %d\n", count) fmt.Printf("Words frequency: \n") //todo: sort words by values for nice print for k, v := range words { fmt.Printf("%s:%d\n", k, v) } }
Results are stored in a map words. The property of map that it doesn’t have defined order of keys, so the bonus here is to sort words map by frequency of words(by values).
See source code at GitHub