AzLearn

تمرين إعادة البناء

Word Frequency Map

أعد كتابة برنامج Go يحسب تكرار الكلمات باستخدام map.

go ~16 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
package main

import (
	"fmt"
	"sort"
	"strings"
	"unicode"
)

func clean(word string) string {
	return strings.TrimFunc(strings.ToLower(word), func(r rune) bool {
		return !unicode.IsLetter(r) && !unicode.IsDigit(r)
	})
}

func frequencies(text string) map[string]int {
	counts := make(map[string]int)
	for _, word := range strings.Fields(text) {
		word = clean(word)
		if word != "" {
			counts[word]++
		}
	}
	return counts
}

func main() {
	text := "Go maps count words. Go maps are small, direct, and useful."
	counts := frequencies(text)

	words := make([]string, 0, len(counts))
	for word := range counts {
		words = append(words, word)
	}
	sort.Strings(words)

	for _, word := range words {
		fmt.Printf("%-8s %d\n", word, counts[word])
	}
}
اكتب هنا