Created
December 14, 2013 17:47
-
-
Save rndD/7962393 to your computer and use it in GitHub Desktop.
count words in file
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
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"regexp" | |
"strings" | |
"sort" | |
) | |
func main() { | |
// read whole the file | |
content, err := ioutil.ReadFile("simple.txt") | |
if err != nil { panic(err) } | |
str := string(content) | |
words := regexp.MustCompile("\\w+").FindAllString(str, -1) | |
dict := make(map[string]int) | |
for _, word := range words { | |
word = strings.ToLower(word) | |
if _, ok := dict[word] ; ok { | |
dict[word]++ | |
}else{ | |
dict[word] = 1 | |
} | |
} | |
vs := NewValSorter(dict) | |
vs.Sort() | |
for i := 0; i < len(vs.Keys); i++ { | |
fmt.Printf("%20s -> ", vs.Keys[i]) | |
fmt.Printf("%d\n", vs.Vals[i]) | |
} | |
} | |
type ValSorter struct { | |
Keys []string | |
Vals []int | |
} | |
func NewValSorter(m map[string]int) *ValSorter { | |
vs := &ValSorter{ | |
Keys: make([]string, 0, len(m)), | |
Vals: make([]int, 0, len(m)), | |
} | |
for k, v := range m { | |
vs.Keys = append(vs.Keys, k) | |
vs.Vals = append(vs.Vals, v) | |
} | |
return vs | |
} | |
func (vs *ValSorter) Sort() { | |
sort.Sort(vs) | |
} | |
func (vs *ValSorter) Len() int { return len(vs.Vals) } | |
func (vs *ValSorter) Less(i, j int) bool { return vs.Vals[i] < vs.Vals[j] } | |
func (vs *ValSorter) Swap(i, j int) { | |
vs.Vals[i], vs.Vals[j] = vs.Vals[j], vs.Vals[i] | |
vs.Keys[i], vs.Keys[j] = vs.Keys[j], vs.Keys[i] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment