This simple generator emits short sentences based on the given text corpus using a Markov chain.
Using a what?
To put it simply - it works kinda like word suggestions that you have while typing messages in your smartphone. It analyzes which word is followed by which in the given corpus and how often. And then, for any given word it tries to predict what the next one might be.
;/* array of your strings which will be used to "train" the generator */;;;console.logresult;
Here you create an instance of
TextGenerator passing an array of strings to it -
it represents your text corpus which will be used to "train" the generator. The more strings/sentences
you pass, the more diverse results you get, so you would better pass like hundreds of them - or even more!
TextGenerator.generateSentence() returns a
null in case it was unable to generate a sentence.
Reading the text corpus from an external file
If you have your texts in an external file, you can pass the path to it as an argument for
TextGenerator's constructor like this:
;;// in this example my texts are located in corpus.txt;;
Getting result as a raw array of strings
If you do not need your result to look like a sentence (i.e. a string starting with a capital and ending with a '.'),
TextGenerator.generate() method instead of
generateSentence(). It returns
the result sentence as an array of words - or
null if the generation process failed.
Then you might want to
join the items or apply any other transformation you like.
TextGenerator.generate() methods accept
parameter that you might use to control the generation process.
You can use the following optional parameters:
wordToStart- which word should be used to start the Markov chain - and therefore the result sentence. If unspecified, a random word is used;
minWordCount- minimum number of words that are supposed to be in the generated sentence. Default is
maxWordCount- maximum number of words that are supposed to be in the generated sentence. Default is
retryCount- since the generation process is rather probabilistic, sometimes the generator might not be able to get a result on the first try, so it may need some more attempts. Default is
contextUsageDegree- a number from
1To avoid diving into details, this parameter defines the degree of similarity between the generated sentences and the sentences in the source text corpus. The less the number is, the more nonsence sentences you get. Default is
In case you want to specify any of these parameters, do it like this:
regexpu is used for transpiling regular expressions with unicode property escapes into good old and nodejs8-compatible ES5 format.