gpt4 book ai didi

go - 查找文本中出现次数最多的字符

转载 作者:IT王子 更新时间:2023-10-29 02:32:43 25 4
gpt4 key购买 nike

我需要实现一个带有接口(interface)的包,该接口(interface)带有获取文本文件并对其进行分析的方法——计算字符总数并找到最常见的符号和单词。为了找到最常见的字符,我循环遍历文本中的每个 rune ,将其转换为字符串并将其作为键附加到 map。该值是一个递增的计数器,用于计算该字符在给定文本中出现的频率。现在我遇到了以下问题——我无法弄清楚如何在我的 map 中获取具有最高值的键。这是代码:

package textscanner

import (
"fmt"
"log"
"io/ioutil"
"unicode/utf8"
"strconv"
)

// Initializing my scanner
type Scanner interface {
countChar(text string) int

frequentSym(text string) // Return value is not yet implemented

Scan()

Run()
}

/* method counting characters */
func countChar(sc Scanner, text string) int { ... }

func frequentSym(sc Scanner, text string) {
// Make a map with string key and integer value
symbols := make(map[string] int)

// Iterate through each char in text
for _, sym := range text {
// Convert rune to string
char := strconv.QuoteRune(sym)
// Set this string as a key in map and assign a counter value
count := symbols[char]

if count == symbols[char] {
// increment the value
symbols[char] = count + 1
} else {
symbols[char] = 1
}
}
}

所以,基本上我需要找到一个具有最高 int 值的对,并返回一个与其对应的 string 键,即文本中出现频率最高的字符

最佳答案

只需遍历 map :

maxK := ""
maxV := 0
for k, v := range symbols {
if v > maxV {
maxV = v
maxK = k
}
}
// maxK is the key with the maximum value.

关于go - 查找文本中出现次数最多的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42857479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com