| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- package main
- import (
- "fmt"
- "os"
- "path/filepath"
- "sort"
- )
- /* Pair type */
- type Pair struct {
- key string
- value int
- }
- /* Pair Slice type */
- type PairSlice []Pair
- /* Functions used for sort */
- func (s PairSlice) Len() int {
- return len(s)
- }
- func (s PairSlice) Swap(i, j int) {
- s[i], s[j] = s[j], s[i]
- }
- func (s PairSlice) Less(i, j int) bool {
- if s[i].value == s[j].value {
- return s[i].key < s[j].key
- } else {
- return s[i].value > s[j].value
- }
- }
- func main() {
- const path = "../testdata"
- dataDir, err := os.ReadDir(path)
- if err != nil {
- fmt.Println("Directory not found!")
- return
- }
- dict := make(map[string]int)
- for _, file := range dataDir {
- if file.IsDir() {
- continue
- }
- text, _ := os.ReadFile(filepath.Join(path, file.Name()))
- word := ""
- for i := range text {
- if text[i] >= 'A' && text[i] <= 'Z' {
- text[i] += 'a' - 'A' // to lower case
- }
- if text[i] >= 'a' && text[i] <= 'z' || word != "" && text[i] == '\'' {
- word += string(text[i])
- } else if word != "" {
- dict[word]++
- word = ""
- }
- }
- if word != "" {
- dict[word]++
- }
- }
- answer := make(PairSlice, 0)
- for word, cnt := range dict {
- answer = append(answer, Pair{word, cnt})
- }
- sort.Sort(answer)
- for _, pair := range answer {
- fmt.Printf("%s\t%d\n", pair.key, pair.value)
- }
- }
|