generates a markov chain of words based on input files
markovchain generates a markov chain based on text passed into it.
var MarkovChain = require'markovchain'fs = require'fs'quotes = fsreadFileSync'./quotes.txt' 'utf8'console.logquotesstart'The'end5process
This will read a file, "quotes.txt", generate a word chain, then attempt to generate sentences starting with the word
"The" that are 5 words long, and then output to console.
content: the content that you want passed into the markov chain
normalizeFn: the function to apply to every word (generally to clean it up,
e.g. removing commas and other non-letter words)
start method can take in either a
string str, in which case it will look
to use that word to start the sentence.
If you instead pass a
function func with one parameter,
wordList, you will
be given the entire list of word chains in which you can decide what words to
use to start a sentence. For example, you can generate sentences based on the
number of times a word occurs, or if the word starts with a capital letter.
varvar tmpList = ObjectkeyswordListfilterreturn word0 >= 'A' && word0 <= 'Z'return tmpList~~Mathrandom*tmpListlengthconsole.logquotesstartuseUpperCaseendprocess
end method can take a
str, the markov chain will generate words until the word matches
stror the generator can no longer find words to chain.
int, the markov chain will generate words until the sentence length matches
intor the generator can no longer find words to chain.
func, the markov chain will generate words until function
funcwill be passed one parameter,
sentencethat returns the generated sentence so far
// same as passing value, 5 to end functionvarreturn sentencesplit" "length >= 5console.logquotesstartuseUpperCaseendstopAfterFiveWordsprocess
end, the markov chain will generate words until it can no longer find words to chain.
parse function adds more content to the markov chain. This allows you to
content later on, rather than needing all the next when you instantiate the
If you pass a second parameter,
parseBy, it specifies how the content will be
parsed into sentences (which are then further parsed down into words). By
parseBy will parse into newlines, periods, and question marks.
var m = 'some text here'mparse'add additional text'console.logmparse'more and more text'end5process
var MarkovChain = require('markovchain').MarkovChain
end()has changed a little bit, before the markov chain would continue until the Function passed returned false, now the Function being passed into
end()should only return true when you want the markov chain generator to stop generating the sentence.
startcan now accept a Function instead of just a String