-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
freq.go
46 lines (38 loc) · 837 Bytes
/
freq.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package textfiles
import (
"fmt"
"log"
"os"
"sort"
"strings"
)
func Frequency(fileName string, min int) {
bs, err := os.ReadFile(fileName)
if err != nil {
log.Fatal(err)
}
text := B2S(bs)
fields := strings.FieldsFunc(text, func(r rune) bool {
// return !('a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' || r == '\'')
return ('a' > r || r > 'z') && ('A' > r || r > 'Z') && r != '\''
})
wordsCount := make(map[string]int)
for _, field := range fields {
if len(field) >= min {
wordsCount[field]++
}
}
keys := make([]string, 0, len(wordsCount))
for key := range wordsCount {
keys = append(keys, key)
}
sort.Slice(keys, func(i, j int) bool {
return wordsCount[keys[i]] > wordsCount[keys[j]]
})
for i, key := range keys {
fmt.Printf("%s %d\n", key, wordsCount[key])
if i == 30 {
break
}
}
}