Created
April 22, 2017 05:25
-
-
Save Trshant/e0b06277eb3974bdddc0e7121811c9e7 to your computer and use it in GitHub Desktop.
bits of markov.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function create(trigram_dict ){ | |
new_string_arr = ["Yo","mama"]; | |
prevword=trigram_dict [ new_string_arr[new_string_arr.length-2]; | |
pprevword=new_string_arr[new_string_arr.length-1] ; | |
while( typeof( trigram_dict [prevword+' '+pprevword] ) != "undefined" ){ | |
candidate_words = trigram_dict [ prevword+' '+pprevword ] ; | |
//select word randomly out of all candidates | |
item = candidate_words[Math.floor( | |
Math.random() * candidate_words.length)]; | |
new_string_arr.push(item); | |
prevword=trigram_dict [ new_string_arr[new_string_arr.length-2]; | |
pprevword=new_string_arr[new_string_arr.length-1] ; | |
} | |
new_str = new_string_arr.join(" "); | |
//A brand new sentence | |
return new_str ; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trigram_dict = {}; | |
str_arr.forEach( function(e,i){ | |
sent = e; | |
word_tokens = str.split(" "); | |
word_tokens.forEach( | |
function(e,i){ | |
if( i < 1 ){ return true; } | |
if( i == ( word_tokens.length - 1 ) ){ return true; } | |
// check if key (previous-word current-word) present | |
if( !trigram_dict[ word_tokens[i-1]+' '+e] ){ | |
trigram_dict[ word_tokens[i-1]+' '+e] = [] ; | |
} | |
//check if next-word available | |
if( typeof(word_tokens[i+1]) != "undefined" ){ | |
trigram_dict[word_tokens[i-1]+' '+e].push(word_tokens[i+1] ); | |
} | |
} | |
); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment