| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 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
- }
- return s[i].value > s[j].value
- }
- func main() {
- const path = "../testdata"
- dataDir, err := os.ReadDir(path) // get directory info
- if err != nil {
- fmt.Println("Directory not found!")
- return
- }
- dict := make(map[string]int) // store count in map
- for _, file := range dataDir {
- if file.IsDir() {
- continue
- }
- text, _ := os.ReadFile(filepath.Join(path, file.Name())) // read file content
- 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]) // extend word
- } else if word != "" {
- dict[word]++ // update map
- word = ""
- }
- }
- if word != "" {
- dict[word]++ // update map
- }
- }
- answer := make(PairSlice, 0)
- for word, cnt := range dict {
- answer = append(answer, Pair{word, cnt}) // get answer from map
- }
- sort.Sort(answer)
- for _, pair := range answer {
- fmt.Printf("%s\t%d\n", pair.key, pair.value)
- }
- }
|