-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
freq2.go
53 lines (39 loc) · 816 Bytes
/
freq2.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
47
48
49
50
51
52
53
package textfiles
import (
"fmt"
"io/ioutil"
"log"
"regexp"
"sort"
)
type WordFreq struct {
word string
freq int
}
func (p WordFreq) String() string {
return fmt.Sprintf("%s %d", p.word, p.freq)
}
func Frequency2(filename string) {
// filename = "the-king-james-bible.txt"
reg := regexp.MustCompile("[a-zA-Z']+")
bs, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
text := string(bs)
matches := reg.FindAllString(text, -1)
words := make(map[string]int)
for _, match := range matches {
words[match]++
}
var wordFreqs []WordFreq
for k, v := range words {
wordFreqs = append(wordFreqs, WordFreq{k, v})
}
sort.Slice(wordFreqs, func(i, j int) bool {
return wordFreqs[i].freq > wordFreqs[j].freq
})
for i := 0; i < 10; i++ {
fmt.Println(wordFreqs[i])
}
}