我有一个简单的输入字符串,我需要阅读并计算重复的单词。
但是,在执行此操作时,我需要将字符串转换为小写字母,但有些函数如何将函数ToLower无效。
我已附上golang链接,请帮助我了解可能出现的问题。
https://play.golang.org/p/OnQW-pgQxqq
同样粘贴代码。
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, "\n")
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
}
答案 0 :(得分:1)
因此,基于docs,strings.ToLower
需要一个字符串并且RETURNS是一个字符串,所以基本上你必须将ToLower
的结果赋给一个变量,如下所示诀窍
line = strings.ToLower(string(line))