I have a simple input string which I need to read and count the repeated words.
But, while doing that I need to convert the string to lower case, but some how the func ToLower is not working.
I have attached the golang link, Please, help me understand what can be the issue.
https://play.golang.org/p/OnQW-pgQxqq
Also pasting the code.
func main() {
input := `
one
two Two
three Three Three;
four four four, four
five? five. five, five Five`
countwords(input)
}
type kv struct {
key string
val int
}
type kvlist []kv
// need to define custome interface to make this work:
func (kv kvlist) Less(i, j int) bool { return kv[i].val < kv[j].val }
func (kv kvlist) Swap(i, j int) { kv[i], kv[j] = kv[j], kv[i] }
func (kv kvlist) Len() int { return len(kv) }
//sort the words by value
func sortmap(wordmap map[string]int) []kv {
list := make(kvlist, len(wordmap))
i := 0
for k, v := range wordmap {
list[i] = kv{k, v}
i++
}
// we need to make few more modification to change this but,
// for now lets assume it works.
sort.Sort(sort.Reverse(list))
return list
}
func countwords(str string) []kv {
count := make(map[string]int)
reg, err := regexp.Compile("[^a-zA-Z0-9 ]+")
if err != nil {
log.Fatal(err)
}
lines := strings.Split(str, "
")
for _, line := range lines {
line := reg.ReplaceAllString(line, "")
strings.ToLower(string(line))
repeatwords := strings.Fields(line) // count the repeated words
fmt.Println(repeatwords)
for _, word := range repeatwords {
if _, ok := count[word]; ok {
count[word]++
} else {
count[word] = 1
}
}
}
//once counted now sort the map based on values(repeated words).
ret := sortmap(count)
fmt.Println(count)
return ret
}