Go语言之旅练习#23:我的单词计数器不起作用

huangapple go评论98阅读模式
英文:

Tour of Go Exercise #23: my word counter doesn't work

问题

我正在尝试解决go tour #23中的谜题,但我不明白为什么我的单词计数器不起作用。print似乎打印了预期的值,但测试只看到1,而不管计数是多少。

package main

import (
	"strings"
	"unicode/utf8"

	"golang.org/x/tour/wc"
)

func WordCount(s string) map[string]int {
	// 将字符串按空格分割成切片
	ws := strings.Fields(s)
	// 创建一个新的映射
	c := make(map[string]int)
	// 遍历每个单词
	for _, v := range ws {
		c[v] = utf8.RuneCountInString(v)
	}

	print(c["am"])

	return c
}

func main() {
	wc.Test(WordCount)
}

可以在这里找到playground。

英文:

I'm trying to resolve the puzzle from go tour #23 and I don't understand why my word counter doesn't work. print seems to print the expected value but the tests sees only 1 regardless the count.

package main

import (
	"strings"
	"unicode/utf8"

	"golang.org/x/tour/wc"
)

func WordCount(s string) map[string]int {
	// explode the string into a slice without whitespaces
	ws := strings.Fields(s)
	//make a new map
	c := make(map[string]int)
	//iterate over each word
	for _, v := range ws {
		c[v] = utf8.RuneCountInString(v)
	}

	print(c["am"])

	return c
}

func main() {
	wc.Test(WordCount)
}

The playground is available here

答案1

得分: 2

你正在解决错误的问题。它不要求你计算每个单词的长度,而是要求计算每个单词出现的次数。将以下代码:

c[v] = utf8.RuneCountInString(v)

改为:

c[v] += 1 // 或者 c[v]++
英文:

You're solving the wrong problem. It doesn't ask you for the length of each word, but for the number of times each word occurs. Change

c[v] = utf8.RuneCountInString(v)

for

c[v] += 1 // or c[v]++

答案2

得分: 1

问题是 c[v] = utf8.RuneCountInString(v)。它有两个问题:

  1. 每次重新遇到一个单词时,你都会重置计数器。你应该增加计数器,而不是重置。

  2. 你将单词中的符文数设置为计数器的值。谜题是“文本中一个单词出现的次数”,所以只需像 c[v] = c[v] + 1 这样做(如果条目为空,则默认为0)。

此外,我会对文本进行规范化处理-去除标点符号并将所有字母转为小写。

英文:

The problem is c[v] = utf8.RuneCountInString(v). It has two problems:

  1. You're resetting the counter for each word every time you re-encounter it. You should increment, not set.

  2. You are setting the number of runes in the word to the counter. The puzzle is "how many times a word appears in the text". so just do something like c[v] = c[v] + 1 (if the entry is empty it will default to 0)

Also, I'd normalize the text - strip punctuation marks and lowercase everything.

huangapple
  • 本文由 发表于 2014年3月25日 19:03:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/22632594.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定