/
main.go
104 lines (88 loc) · 2.21 KB
/
main.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 main
import (
"bufio"
"compress/gzip"
"encoding/gob"
"flag"
"fmt"
markov "github.com/Nightgunner5/markov/lib"
"io"
"math/rand"
"os"
"strings"
"time"
)
var (
seed = flag.Int64("seed", time.Now().UnixNano(), "the random seed to use when generating text.")
output = flag.String("o", "", "if non-empty, the file to write output to. defaults to standard output.")
input = flag.String("i", "", "if non-empty, the file to read input from. defaults to standard input.")
c = flag.Bool("c", false, "compile the input to a reusable markov chain cache instead of generating text.")
p = flag.Bool("p", false, "if this is set, the input will be parsed as a reusable markov chain cache.")
n = flag.Int("n", 5, "the number of lines of text to generate")
)
var startup = func() {}
var cleanup = func() {}
func main() {
var err error
flag.Parse()
startup()
defer cleanup()
r := rand.New(rand.NewSource(*seed))
in := os.Stdin
if *input != "" {
in, err = os.Open(*input)
if err != nil {
fmt.Fprintf(os.Stderr, "error while opening -i file: %s\n", err)
return
}
defer in.Close()
}
out := os.Stdout
if *output != "" {
out, err = os.Create(*output)
if err != nil {
fmt.Fprintf(os.Stderr, "error while opening -o file: %s\n", err)
return
}
defer out.Close()
}
b := bufio.NewReaderSize(in, 0x10000)
chain := markov.NewSTChain()
if *p {
g, err := gzip.NewReader(b)
if err != nil {
fmt.Fprintf(os.Stderr, "error while reading precompiled file: %s\n", err)
return
}
err = gob.NewDecoder(g).Decode(&chain)
g.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error while reading precompiled file: %s\n", err)
return
}
} else {
for {
line, err := b.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
fmt.Fprintf(os.Stderr, "error while reading input: %s\n", err)
return
}
chain.Build(strings.Fields(line))
}
}
if *c {
g, _ := gzip.NewWriterLevel(out, gzip.BestCompression)
err = gob.NewEncoder(g).Encode(chain)
g.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error while writing compiled file: %s\n", err)
return
}
} else {
for i := 0; i < *n; i++ {
fmt.Fprintln(out, chain.Generate(100, r))
}
}
}