<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ngram Generator</title>
</head>
<body>
<h1>Ngram Generator</h1>
<button onclick="eatText()">Eat Text</button>
<button onclick="generateText()">Generate Text</button><br>
<textarea id="output-text" rows="20" cols="80"></textarea><br>
<script>
let markovChain = {};
function eatText() {
let text = document.getElementById("output-text").value;
let words = text.match(/\b\w+\b|[^\s\w]+|\t|\r|\n/g);
for (let i = 0; i < words.length - 1; i++) {
let currentWord = words[i];
let nextWord = words[i + 1];
if (!markovChain[currentWord]) {
markovChain[currentWord] = [];
}
markovChain[currentWord].push(nextWord);
}
document.getElementById("output-text").value ="";
}
function generateText() {
let numWords = parseInt(prompt("How many words do you want to generate?"));
let words = Object.keys(markovChain);
let word = words[Math.floor(Math.random() * words.length)];
let result = [];
for (let i = 0; i < numWords; i++) {
result.push(word);
let newWords = markovChain[word];
word = newWords[Math.floor(Math.random() * newWords.length)];
if (!word) {
word = words[Math.floor(Math.random() * words.length)];
}
}
document.getElementById("output-text").value = result.join(" ");
}
</script>
</body>
</html>
No comments:
Post a Comment