Bài tập Go

Word Frequency Counter in Go

Count how often each word appears with a map and print the most common ones.

  • Cơ bản
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • strings.Fields
  • counts[word]++
  • Sorting by count
counts
"the"3
"brown"1
"dog"1

The 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.

Những điểm quan trọng

  1. A missing key reads as 0, so ++ just works.
  2. Sort by count, then by word.
  3. words[:3] keeps the top three.

Ví dụ Go chạy được

Go
Chạy code →
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])
	}
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
the: 3
brown: 1
dog: 1

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách