Exercices Go
Word Frequency Counter in Go
Count how often each word appears with a map and print the most common ones.
Ce que vous allez apprendre
- strings.Fields
- counts[word]++
- Sorting by count
counts
"the"3"brown"1"dog"1The word is the key, the count is the value
Counting words is a typical job for a map: the word is the key and the number of times it appears is the value.
counts[word]++ works even for a new word, because a missing key reads as 0. The words are then sorted by count, highest first, and alphabetically when the counts are equal, so the output is always the same.
Points clés
- A missing key reads as 0, so ++ just works.
- Sort by count, then by word.
words[:3]keeps the top three.
Exemple Go exécutable
main.go
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
text := "the quick brown fox jumps over the lazy dog the end"
counts := map[string]int{}
for _, word := range strings.Fields(text) {
counts[word]++
}
words := make([]string, 0, len(counts))
for word := range counts {
words = append(words, word)
}
sort.Slice(words, func(i, j int) bool {
if counts[words[i]] != counts[words[j]] {
return counts[words[i]] > counts[words[j]]
}
return words[i] < words[j]
})
for _, word := range words[:3] {
fmt.Printf("%s: %d\n", word, counts[word])
}
}
the: 3
brown: 1
dog: 1S'entraîner
Ouvrez l'exemple dans le compilateur en ligne, modifiez une valeur ou ajoutez une ligne, et devinez la sortie avant de l'exécuter. Cassez ensuite le code exprès et lisez le message du compilateur.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
S'entraîner avec un défi
Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.
- Compter les mots Comptez le nombre de mots dans une phrase. Facile
- Fréquence des caractères Comptez combien de fois chaque caractère apparaît. Facile