main.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 {
  49. for word != "" && word[len(word)-1] == '\'' {
  50. word = word[:len(word)-1] // remove trailing quotation mark
  51. }
  52. if word != "" {
  53. dict[word]++ // update map
  54. word = ""
  55. }
  56. }
  57. }
  58. for word != "" && word[len(word)-1] == '\'' {
  59. word = word[:len(word)-1] // remove trailing quotation mark
  60. }
  61. if word != "" {
  62. dict[word]++ // update map
  63. }
  64. }
  65. answer := make(PairSlice, 0)
  66. for word, cnt := range dict {
  67. answer = append(answer, Pair{word, cnt}) // get answer from map
  68. }
  69. sort.Sort(answer)
  70. for _, pair := range answer {
  71. fmt.Printf("%s %d\n", pair.key, pair.value)
  72. }
  73. }