main.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "sort"
  7. )
  8. /* Pair type */
  9. type Pair struct {
  10. key string
  11. value int
  12. }
  13. /* Pair Slice type */
  14. type PairSlice []Pair
  15. /* Functions used for sort */
  16. func (s PairSlice) Len() int {
  17. return len(s)
  18. }
  19. func (s PairSlice) Swap(i, j int) {
  20. s[i], s[j] = s[j], s[i]
  21. }
  22. func (s PairSlice) Less(i, j int) bool {
  23. if s[i].value == s[j].value {
  24. return s[i].key < s[j].key
  25. }
  26. return s[i].value > s[j].value
  27. }
  28. func main() {
  29. const path = "../testdata"
  30. dataDir, err := os.ReadDir(path) // get directory info
  31. if err != nil {
  32. fmt.Println("Directory not found!")
  33. return
  34. }
  35. dict := make(map[string]int) // store count in map
  36. for _, file := range dataDir {
  37. if file.IsDir() {
  38. continue
  39. }
  40. text, _ := os.ReadFile(filepath.Join(path, file.Name())) // read file content
  41. word := ""
  42. for i := range text {
  43. if text[i] >= 'A' && text[i] <= 'Z' {
  44. text[i] += 'a' - 'A' // to lower case
  45. }
  46. if text[i] >= 'a' && text[i] <= 'z' || word != "" && text[i] == '\'' {
  47. word += string(text[i]) // extend word
  48. } else if word != "" {
  49. dict[word]++ // update map
  50. word = ""
  51. }
  52. }
  53. if word != "" {
  54. dict[word]++ // update map
  55. }
  56. }
  57. answer := make(PairSlice, 0)
  58. for word, cnt := range dict {
  59. answer = append(answer, Pair{word, cnt}) // get answer from map
  60. }
  61. sort.Sort(answer)
  62. for _, pair := range answer {
  63. fmt.Printf("%s\t%d\n", pair.key, pair.value)
  64. }
  65. }