90
sketches/MarkovChain.js
Normal file
90
sketches/MarkovChain.js
Normal file
@@ -0,0 +1,90 @@
|
||||
let trainingText = "";
|
||||
let wordList = [];
|
||||
let wordListPlain = [];
|
||||
let startWord = "";
|
||||
let finalText = "";
|
||||
let cleanedText = "";
|
||||
async function setup() {
|
||||
trainingText = await loadStrings('assets/text/cpdv_text_only.txt');
|
||||
createCanvas(windowWidth, windowHeight)
|
||||
background(255, 255, 230)
|
||||
|
||||
console.log(trainingText);
|
||||
trainingText = splitText(trainingText);
|
||||
console.log(trainingText);
|
||||
for (i = 0; i < trainingText.length; i++) {
|
||||
if (wordList.indexOf(trainingText[i]) == -1) {
|
||||
if (i % 1000 == 0) {
|
||||
console.log('i',i);
|
||||
}
|
||||
wordList.push([trainingText[i], []]);
|
||||
wordListPlain.push(trainingText[i]);
|
||||
for (j = i; j < trainingText.length; j++) {
|
||||
if (trainingText[j] == wordList[wordList.length - 1][0]) {
|
||||
if (trainingText[j + 1] != undefined){
|
||||
wordList[wordList.length - 1][1].push(trainingText[j + 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(wordList);
|
||||
startWord = wordList[round(random(0, wordList.length - 1))][0];
|
||||
finalText = startWord;
|
||||
|
||||
for (i = 0; i < 100; i++) {
|
||||
startWord = generateNextWord(startWord);
|
||||
console.log(startWord)
|
||||
finalText += " " + startWord;
|
||||
}
|
||||
|
||||
textSize(19)
|
||||
console.log(finalText)
|
||||
text(finalText, 10, height / 2)
|
||||
}
|
||||
|
||||
function splitText(text) {
|
||||
for (i = 0; i < text.length; i++) {
|
||||
cleanedText += " " + text[i];
|
||||
}
|
||||
cleanedText = cleanedText
|
||||
.replaceAll(".", " . ")
|
||||
.replaceAll("!", " ! ")
|
||||
.replaceAll("?", " ? ")
|
||||
.replaceAll(",", " , ")
|
||||
.replaceAll(";", " ; ")
|
||||
.replaceAll(":", " : ")
|
||||
.replaceAll('"', ' " ')
|
||||
.replaceAll("'", " ' ")
|
||||
.replaceAll(" "," ")
|
||||
.replaceAll(" "," ")
|
||||
.split(" ");
|
||||
return cleanedText;
|
||||
}
|
||||
|
||||
function generateNextWord(currentWord) {
|
||||
let currentWordIndex = getWordIndex(currentWord);
|
||||
let nextWordIndex = round(
|
||||
random(
|
||||
0, wordList[currentWordIndex][1].length - 1
|
||||
)
|
||||
);
|
||||
//retun . if end of text
|
||||
if (wordList[currentWordIndex][1][nextWordIndex] == undefined){
|
||||
return '.';
|
||||
}
|
||||
return wordList[currentWordIndex][1][nextWordIndex];
|
||||
|
||||
}
|
||||
|
||||
function getWordIndex(word) {
|
||||
return wordListPlain.indexOf(word);
|
||||
}
|
||||
|
||||
function draw() {
|
||||
|
||||
}
|
||||
|
||||
function mousePressed() {
|
||||
}
|
||||
Reference in New Issue
Block a user