-
Notifications
You must be signed in to change notification settings - Fork 0
/
lang.go
66 lines (58 loc) · 1.07 KB
/
lang.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
package lang
import "math"
var englishLetterFrequencies = map[byte]float64{
'a': 0.08167,
'b': 0.01492,
'c': 0.02782,
'd': 0.04253,
'e': 0.12702,
'f': 0.02228,
'g': 0.02015,
'h': 0.06094,
'i': 0.06966,
'j': 0.00153,
'k': 0.00772,
'l': 0.04025,
'm': 0.02406,
'n': 0.06749,
'o': 0.07507,
'p': 0.01929,
'q': 0.00095,
'r': 0.05987,
's': 0.06327,
't': 0.09056,
'u': 0.02758,
'v': 0.00978,
'w': 0.02360,
'x': 0.00150,
'y': 0.01974,
'z': 0.00074,
}
func countByteFrequency(bs []byte) map[byte]float64 {
counts := make(map[byte]float64)
n := 0
for _, c := range bs {
counts[c]++
n++
}
for b := range counts {
counts[b] /= float64(n)
}
return counts
}
func bhattacharyyaCoefficient(f, g map[byte]float64) float64 {
sum := 0.0
for b, freq := range f {
sum += math.Sqrt(freq * g[b])
}
return sum
}
func ScoreEnglishTextByteFrequencies(freqs map[byte]float64) float64 {
return bhattacharyyaCoefficient(
englishLetterFrequencies,
freqs)
}
func ScoreEnglishText(text []byte) float64 {
return ScoreEnglishTextByteFrequencies(
countByteFrequency(text))
}