-
Notifications
You must be signed in to change notification settings - Fork 1
/
reader.go
83 lines (72 loc) · 1.64 KB
/
reader.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
package main
import (
"bufio"
"encoding/gob"
"errors"
"io/ioutil"
"os"
"strconv"
"strings"
)
func makeSentence(s string) (*Sentence, error) {
lines := strings.Split(s, "\n")
if len(lines) < 4 {
return nil, errors.New("Invalid line")
}
words := strings.Split(strings.TrimSpace(lines[0]), "\t")
posTags := strings.Split(strings.TrimSpace(lines[1]), "\t")
heads := strings.Split(strings.TrimSpace(lines[3]), "\t")
sent := make([]*Word, 0)
sent = append(sent, makeRootWord())
for i := 0; i < len(words); i++ {
head, err := strconv.ParseInt(heads[i], 10, 0)
if err != nil {
return nil, err
}
sent = append(sent, makeWord(words[i], posTags[i], i+1, int(head)))
}
return &Sentence{sent}, nil
}
func splitBySentence(s string) []string {
return strings.Split(s, "\n\n")
}
func ReadData(filename string) ([]*Sentence, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(bufio.NewReader(file))
if err != nil {
return nil, err
}
sentences := make([]*Sentence, 0)
for _, sent := range splitBySentence(string(data)) {
s, err := makeSentence(sent)
if err != nil {
break
}
sentences = append(sentences, s)
}
return sentences, nil
}
func SaveModel(weight *[]float64, filename string) error {
file, err := os.Create(filename)
defer file.Close()
if err != nil {
return err
}
enc := gob.NewEncoder(file)
enc.Encode(&weight)
return nil
}
func LoadModel(filename string) (*[]float64, error) {
var w []float64
file, err := os.Open(filename)
defer file.Close()
if err != nil {
return nil, err
}
decoder := gob.NewDecoder(file)
decoder.Decode(&w)
return &w, nil
}