-
Notifications
You must be signed in to change notification settings - Fork 5
/
processor.go
104 lines (89 loc) · 2.04 KB
/
processor.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
package topics
import (
"bufio"
"io"
"os"
"strings"
)
func NewDefaultProcessor() *Processor {
return NewProcessor(
Transformations{ToLower, Sanitize, GetStopwordFilter("stopwords/en")},
)
}
func NewProcessor(transformations Transformations) *Processor {
return &Processor{
transformations: transformations,
}
}
func (p *Processor) AddStrings(corpus *Corpus, docs []string) *Corpus {
for _, doc := range docs {
err := p.AddDoc(corpus, strings.NewReader(doc))
if err != nil {
panic(err)
}
}
return corpus
}
func (p *Processor) AddReaders(corpus *Corpus, docs []io.Reader) *Corpus {
for _, doc := range docs {
err := p.AddDoc(corpus, doc)
if err != nil {
panic(err)
}
}
return corpus
}
func (p *Processor) AddDoc(corpus *Corpus, doc io.Reader) error {
document, err := p.processDocument(doc, "", corpus.Vocabulary)
if err != nil {
panic(err)
}
corpus.Documents = append(corpus.Documents, *document)
return nil
}
func (p *Processor) processDocument(input io.Reader, name string, vocab *Vocabulary) (*Document, error) {
s := bufio.NewScanner(input)
s.Split(bufio.ScanWords)
document := NewDocument(name)
for s.Scan() {
w := s.Text()
w, keep := p.transform(w)
if !keep {
continue
}
document.Add(vocab.Set(w))
}
return document, nil
}
func (p *Processor) transform(w string) (string, bool) {
var keep bool
for _, t := range p.transformations {
w, keep = t(w)
if !keep || w == "" {
return "", false
}
}
return w, true
}
// Process one document corpus
func (p *Processor) ImportSingleFileCorpus(corpus *Corpus, path string) (*Corpus, error) {
docs, err := p.importSingleFileCorpus(path)
if err != nil {
return nil, err
}
return p.AddStrings(corpus, docs), err
}
// Read one document per line
func (p *Processor) importSingleFileCorpus(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}