generates a markov chain of words based on input files
markovchain generates a markov chain of words based on input files
- npm install markovchain
var MarkovChain = require'markovchain'MarkovChainquotes = files: 'quotes.txt'quotesstart'The' //end5processconsole.logs
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.
start method can take in either a
String, in which case it will look to use that word to start the sentence.
If you instead pass a
Function 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 = ObjectkeyswordListfilter return word0 >= 'A' && word0 <= 'Z'return tmpList~~Mathrandom*tmpListlengthquotesstartuseUpperCaseendprocess console.logsentence
end method can take a
- If you pass a String,
str, the markov chain will generate words until the word matches
stror the generator can no longer find words to chain.
- If you pass a Number,
num, the markov chain will generate words until the sentence length matches
numor the generator can no longer find words to chain.
- If you pass a Function,
fn, the markov chain will generate words until function
fnwill be passed one parameter,
sentencethat returns the generated sentence so far
// same as passing value, 5 to end functionvarreturn sentencesplit" "length >= 5quotesstartuseUpperCaseendstopAfterFiveWordsprocessconsole.logsentence
- If you pass nothing in
end, the markov chain will generate words until it can no longer find words to chain.
- Passing a Function into
endhas 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
- The logic to split sentences has changed from just a newline, to both a newline and a period.
- Also previous versions changed all the words to strip them of any non-letters/numbers and also lowercased them. This version now doesn't modify the string other than to delete a period at the end of a word.
- Small change to how words are stripped
- Initial Release