Documentation ¶
Overview ¶
Package markov provides a markov chain implementation which allows you to "train" a model using any form of text as input. The markov chain will split the text sequence into pairs and then generate the transition mapping.
A Builder implementation also exists, this can be generated on top of a chain in order to generate a continuous flow of new words.
MIT License Copyright (c) 2019 Alexandru-Paul Copil
Example (Basic) ¶
This example shows a general usecase for the Markov Chain and the builder. It takes input from `stdin` and trains the markov chain then generates a given number of words nd prints out the fully generated string. The flags can configure the max number of words to generate and the sequence pairing to be used when "training" the markov chain.
package main import ( "flag" "fmt" "io/ioutil" "log" "os" "strings" "cpl.li/go/markov" ) func main() { // handle flags maxWords := flag.Int("words", 100, "max words to generate (default 100)") pairSize := flag.Int("pairs", 2, "size of a word pair (default 2)") flag.Parse() c := markov.NewChain(*pairSize) // create markov chain // read stdin data, err := ioutil.ReadAll(os.Stdin) if err != nil { log.Fatal(err) } // give data as sequence to chain model c.Add(strings.Fields(string(data))) b := c.NewBuilder(nil) // create builder on top of chain b.Generate(*maxWords - c.PairSize) // generate new words fmt.Println(b.String()) // print end product }
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder spawns from a Markov chain and using the generated tokens from it, creates sequences of words.
func (*Builder) Generate ¶
Generate will tell the builder to poll the markov chain for at most `count` new words to append to the builders sequence. The function will return the real number of generated words, 0 meaning no new words could be generated.
type Chain ¶
type Chain struct { PairSize int // contains filtered or unexported fields }
Chain represents a Markov chain composed of given length pairs extracted from provided sequences.
func NewChain ¶
NewChain generates a Chain with pairs of given length.
func (*Chain) Add ¶
Add adds the transition counts to the chain for a given sequence of words.
func (*Chain) NewBuilder ¶
NewBuilder creates a Markov sequence builder form the current chain.
func (*Chain) Next ¶
Next will give you the next possible token for a certain sequence based on a random weighted decision.
type Pair ¶
Pair represents a state transition between a set of 1 or more words and the next word in the Sequence.