-
Notifications
You must be signed in to change notification settings - Fork 0
/
qgram.go
148 lines (111 loc) · 2.1 KB
/
qgram.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package qgram
import (
"io"
"sort"
"unicode"
"github.com/wmentor/tokens"
)
// calc qgram frequency map
func CalcMap(in io.Reader) map[string]int {
result := make(map[string]int)
pushRune := makeCollector(result)
pushWord := func(word string) {
for _, r := range word {
pushRune(r)
}
}
pushRune('_')
wCnt := 0
tokenizer := tokens.New(in)
for {
token, err := tokenizer.Token()
if err != nil {
break
}
if !checkWord(token) {
continue
}
if wCnt > 0 {
pushRune('_')
}
wCnt++
pushWord(token)
}
pushRune('_')
pushRune('_')
return result
}
// all qgrams in lexial order
func QGrams(in io.Reader) []string {
hash := CalcMap(in)
list := make([]string, 0, len(hash))
for ng := range hash {
list = append(list, ng)
}
sort.Strings(list)
return list
}
// first limit ordered by frequency
func Popular(in io.Reader, limit int) []string {
hash := CalcMap(in)
list := make([]string, 0, len(hash))
for ng := range hash {
list = append(list, ng)
}
sort.Slice(list, func(i, j int) bool {
t1 := hash[list[i]]
t2 := hash[list[j]]
return t1 > t2 || t1 == t2 && list[i] < list[j]
})
if len(list) > limit {
list = list[:limit]
}
return list
}
func mapSimilarity(m1, m2 map[string]int) float64 {
all := map[string]bool{}
both := map[string]bool{}
for k := range m1 {
all[k] = true
if _, has := m2[k]; has {
both[k] = true
}
}
for k := range m2 {
all[k] = true
}
if allS := len(all); allS > 0 {
return float64(len(both)) / float64(allS)
}
return 1
}
// calc text similarity
func Similarity(in1 io.Reader, in2 io.Reader) float64 {
return mapSimilarity(CalcMap(in1), CalcMap(in2))
}
func checkWord(word string) bool {
if word == "-" {
return false
}
for _, r := range word {
if !unicode.IsLetter(r) && r != '-' && r != '\'' {
return false
}
}
return true
}
func makeCollector(result map[string]int) func(rune) {
var strs [3]string
i := 0
pushRune := func(r rune) {
str := string(r)
i++
if i >= 4 {
result[strs[0]+str]++
}
strs[0] = strs[1] + str
strs[1] = strs[2] + str
strs[2] = str
}
return pushRune
}