-
Notifications
You must be signed in to change notification settings - Fork 37
/
pokenamer.go
86 lines (77 loc) · 1.67 KB
/
pokenamer.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
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/mb-14/gomarkov"
)
func main() {
train := flag.Bool("train", false, "Train the markov chain")
order := flag.Int("order", 3, "Chain order to use")
flag.Parse()
if *train {
chain := buildModel(*order)
saveModel(chain)
} else {
chain, err := loadModel()
if err != nil {
fmt.Println(err)
return
}
generatePokemon(chain)
}
}
func buildModel(order int) *gomarkov.Chain {
chain := gomarkov.NewChain(order)
for _, data := range getDataset("names.txt") {
chain.Add(split(data))
}
return chain
}
func split(str string) []string {
return strings.Split(str, "")
}
func getDataset(fileName string) []string {
file, _ := os.Open(fileName)
scanner := bufio.NewScanner(file)
var list []string
for scanner.Scan() {
list = append(list, scanner.Text())
}
return list
}
func loadModel() (*gomarkov.Chain, error) {
var chain gomarkov.Chain
data, err := ioutil.ReadFile("model.json")
if err != nil {
return &chain, err
}
err = json.Unmarshal(data, &chain)
if err != nil {
return &chain, err
}
return &chain, nil
}
func saveModel(chain *gomarkov.Chain) {
jsonObj, _ := json.Marshal(chain)
err := ioutil.WriteFile("model.json", jsonObj, 0644)
if err != nil {
fmt.Println(err)
}
}
func generatePokemon(chain *gomarkov.Chain) {
order := chain.Order
tokens := make([]string, 0)
for i := 0; i < order; i++ {
tokens = append(tokens, gomarkov.StartToken)
}
for tokens[len(tokens)-1] != gomarkov.EndToken {
next, _ := chain.Generate(tokens[(len(tokens) - order):])
tokens = append(tokens, next)
}
fmt.Println(strings.Join(tokens[order:len(tokens)-1], ""))
}