How to convert strings to lower case in GO?

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

How to convert strings to lower case in GO?

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我对GO语言还不熟悉,正在处理一个任务,需要编写一段代码来返回文本中单词的频率。然而,我知道单词'Hello'、'HELLO'和'hello'都被计算为'hello',所以我需要将所有字符串转换为小写。

我知道应该使用strings.ToLower(),但我不知道应该在类中的哪个位置包含它。有人可以帮帮我吗?

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "strings"
  7. "time"
  8. )
  9. const DataFile = "loremipsum.txt"
  10. // 返回文本中单词的频率
  11. func WordCount(text string) map[string]int {
  12. fregs := make(map[string]int)
  13. words := strings.Fields(text)
  14. for _, word := range words {
  15. fregs[strings.ToLower(word)] += 1
  16. }
  17. return fregs
  18. }
  19. // 对文本进行多次运行以计算单词频率所需的时间
  20. //
  21. // 返回总共经过的时间
  22. func benchmark(text string, numRuns int) int64 {
  23. start := time.Now()
  24. for i := 0; i < numRuns; i++ {
  25. WordCount(text)
  26. }
  27. runtimeMillis := time.Since(start).Nanoseconds() / 1e6
  28. return runtimeMillis
  29. }
  30. // 打印基准测试结果
  31. func printResults(runtimeMillis int64, numRuns int) {
  32. fmt.Printf("运行次数:%d\n", numRuns)
  33. fmt.Printf("总时间:%d 毫秒\n", runtimeMillis)
  34. average := float64(runtimeMillis) / float64(numRuns)
  35. fmt.Printf("平均时间/次:%0.2f 毫秒\n", average)
  36. }
  37. func main() {
  38. // 读取DataFile文件内容并存储为字符串data
  39. data, err := ioutil.ReadFile("loremipsum.txt")
  40. if err != nil {
  41. log.Fatal(err)
  42. }
  43. // 将[]byte转换为字符串并打印到屏幕上
  44. text := string(data)
  45. fmt.Println(text)
  46. fmt.Printf("%#v", WordCount(string(data)))
  47. numRuns := 100
  48. runtimeMillis := benchmark(string(data), numRuns)
  49. printResults(runtimeMillis, numRuns)
  50. }

希望对你有帮助!

英文:

I am new to the language GO and working on an assignment where i should write a code that return the word frequencies of the text. However I know that the words 'Hello', 'HELLO' and 'hello' are all counted as 'hello', so I need to convert all strings to lower case.

I know that I should use strings.ToLower(), however I dont know where I should Included that in the class. Can someone please help me?

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;io/ioutil&quot;
  5. &quot;log&quot;
  6. &quot;strings&quot;
  7. &quot;time&quot;
  8. )
  9. const DataFile = &quot;loremipsum.txt&quot;
  10. // Return the word frequencies of the text argument.
  11. func WordCount(text string) map[string]int {
  12. fregs := make(map[string]int)
  13. words := strings.Fields(text)
  14. for _, word := range words {
  15. fregs[word] += 1
  16. }
  17. return fregs
  18. }
  19. // Benchmark how long it takes to count word frequencies in text numRuns times.
  20. //
  21. // Return the total time elapsed.
  22. func benchmark(text string, numRuns int) int64 {
  23. start := time.Now()
  24. for i := 0; i &lt; numRuns; i++ {
  25. WordCount(text)
  26. }
  27. runtimeMillis := time.Since(start).Nanoseconds() / 1e6
  28. return runtimeMillis
  29. }
  30. // Print the results of a benchmark
  31. func printResults(runtimeMillis int64, numRuns int) {
  32. fmt.Printf(&quot;amount of runs: %d\n&quot;, numRuns)
  33. fmt.Printf(&quot;total time: %d ms\n&quot;, runtimeMillis)
  34. average := float64(runtimeMillis) / float64(numRuns)
  35. fmt.Printf(&quot;average time/run: %.2f ms\n&quot;, average)
  36. }
  37. func main() {
  38. // read in DataFile as a string called data
  39. data, err:= ioutil.ReadFile(&quot;loremipsum.txt&quot;)
  40. if err != nil {
  41. log.Fatal(err)
  42. }
  43. // Convert []byte to string and print to screen
  44. text := string(data)
  45. fmt.Println(text)
  46. fmt.Printf(&quot;%#v&quot;,WordCount(string(data)))
  47. numRuns := 100
  48. runtimeMillis := benchmark(string(data), numRuns)
  49. printResults(runtimeMillis, numRuns)
  50. }

答案1

得分: 2

当你将单词用作映射键时,应将它们转换为小写。

  1. for _, word := range words {
  2. fregs[strings.ToLower(word)] += 1
  3. }
英文:

You should convert words to lowercase when you are using them as map key

  1. for _, word := range words {
  2. fregs[strings.ToLower(word)] += 1
  3. }

答案2

得分: 0

你需要仔细定义一个单词。例如,将连续的字母和数字转换为小写。

  1. func WordCount(s string) map[string]int {
  2. wordFunc := func(r rune) bool {
  3. return !unicode.IsLetter(r) && !unicode.IsNumber(r)
  4. }
  5. counts := make(map[string]int)
  6. for _, word := range strings.FieldsFunc(s, wordFunc) {
  7. counts[strings.ToLower(word)]++
  8. }
  9. return counts
  10. }

请注意,这是一个示例代码,用于计算字符串中每个单词出现的次数,并将其转换为小写。你可以根据自己的需求进行修改。

英文:

> I get [a:822 a.:110 I want all a in the same. How do i a change the code so that a and a. is the same? – hello123


You need to carefully define a word. For example, a string of consecutive letters and numbers converted to lowercase.

  1. func WordCount(s string) map[string]int {
  2. wordFunc := func(r rune) bool {
  3. return !unicode.IsLetter(r) &amp;&amp; !unicode.IsNumber(r)
  4. }
  5. counts := make(map[string]int)
  6. for _, word := range strings.FieldsFunc(s, wordFunc) {
  7. counts[strings.ToLower(word)]++
  8. }
  9. return counts
  10. }

答案3

得分: 0

要删除所有非单词字符,你可以使用正则表达式:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "regexp"
  7. "strings"
  8. )
  9. func main() {
  10. str1 := "This is some text! I want to count each word. Is it cool?"
  11. re, err := regexp.Compile(`[^\w]`)
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. str1 = re.ReplaceAllString(str1, " ")
  16. scanner := bufio.NewScanner(strings.NewReader(str1))
  17. scanner.Split(bufio.ScanWords)
  18. for scanner.Scan() {
  19. fmt.Println(strings.ToLower(scanner.Text()))
  20. }
  21. }

这段代码会将字符串中的非单词字符替换为空格,并逐个打印出每个单词(转换为小写)。

英文:

to remove all non-word characters you could use a regular expression:

  1. package main
  2. import (
  3. &quot;bufio&quot;
  4. &quot;fmt&quot;
  5. &quot;log&quot;
  6. &quot;regexp&quot;
  7. &quot;strings&quot;
  8. )
  9. func main() {
  10. str1 := &quot;This is some text! I want to count each word. Is it cool?&quot;
  11. re, err := regexp.Compile(`[^\w]`)
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. str1 = re.ReplaceAllString(str1, &quot; &quot;)
  16. scanner := bufio.NewScanner(strings.NewReader(str1))
  17. scanner.Split(bufio.ScanWords)
  18. for scanner.Scan() {
  19. fmt.Println(strings.ToLower(scanner.Text()))
  20. }
  21. }

答案4

得分: -1

请问您需要将这段内容翻译成中文吗?

英文:

See strings.EqualFold.

Here is an example.

huangapple
  • 本文由 发表于 2022年4月4日 19:38:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/71736628.html
匿名

发表评论

匿名网友

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

确定