This repository has been archived by the owner on Oct 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
stopwords.go
123 lines (98 loc) · 1.93 KB
/
stopwords.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
package swan
import (
"bytes"
"strings"
"unicode"
"unicode/utf8"
"golang.org/x/net/html"
)
const (
textChunkLen = 8192
)
var (
unsupportedLangs = map[string]bool{
// According to http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes,
// NB is covered by macrolanguage NO, so don't use.
"nb": true,
"zh": true, // Needs a good segmenter
}
)
func init() {
for k := range unsupportedLangs {
delete(stopwords, k)
}
}
func getArticleTextChunk(a *Article) string {
var b bytes.Buffer
var getText func(n *html.Node)
getText = func(p *html.Node) {
if p.Type == html.TextNode {
b.WriteString(strings.TrimSpace(p.Data))
b.WriteByte(' ')
} else if p.FirstChild != nil {
for n := p.FirstChild; n != nil; n = n.NextSibling {
getText(n)
if b.Len() >= textChunkLen {
return
}
}
}
}
for _, n := range a.Doc.Nodes {
getText(n)
if b.Len() >= textChunkLen {
break
}
}
return b.String()
}
func splitText(t string) (ws []string) {
start := 0
inWord := false
for i, r := range t {
sep := unicode.IsPunct(r) || unicode.IsSpace(r)
if sep {
switch {
case r == '\'': // Accept things like "boy's"
case inWord:
ws = append(ws, t[start:i])
start = i + 1
inWord = false
default:
start += utf8.RuneLen(r)
}
}
inWord = !sep
}
if start < len(t) {
ws = append(ws, t[start:])
}
return
}
func detectLang(a *Article) string {
score := uint(0)
detected := "en"
ws := splitText(getArticleTextChunk(a))
for lang := range stopwords {
count := stopwordCountWs(lang, ws)
if count > score {
detected = lang
score = count
}
}
return detected
}
func stopwordCount(lang string, text string) uint {
ws := splitText(text)
return stopwordCountWs(lang, ws)
}
func stopwordCountWs(lang string, ws []string) uint {
words := stopwords[lang]
count := uint(0)
for _, w := range ws {
if _, ok := words[strings.ToLower(w)]; ok {
count++
}
}
return count
}