I've been trying to create a very very basic Haiku Generator, which parses text from a large dictionary file and then (for now at least) chooses words that have 5 or 7 syllables and outputs them.
Below is my first go at the code, but the problem I'm having right now is that I don't know exactly how to test or run this code. When I put it through my Chrome JS console, I get the error "require is not defined", which is an integral part of the code to parse the data, so I'm not sure how to fix this. Can anyone provide some insight on this?
Here's my code:
var fs = require("fs");
// open the cmu dictionary file for "reading" (the little r)
// cmudict_file = File.open('cmudict.txt', 'r')
var wordArray = [];
var phonemeArray = [];
var syllArray = [];
// When parsing the dictionary file, I want it to output into two arrays of the same length
// The arrays will be parallel, so wordArray[i] will refer to the word
// phonemeArray[i] will refer to the phoneme for that word, and syllArray[i] will refer to the number of syllables in that word.
fs.readFile('cmudict.txt', function(err, data) {
if(err) {
return console.log(err);
}
var lines = data.toString().split("\n");
lines.forEach(function(line) {
line_split = line.split(" ");
wordArray.push(line_split[0]);
phonemeArray.push(line_split[1]);
});
});
//This function will create an array of the number of syllables in each word.
function syllCount(phonemeArray){
var sylls = [];
for (i = 0, x = phonemeArray.length; i < x; i++){
sylls = phonemeArray.match(/\d/);
syllArray.push(sylls.length);
}
}
//Here I want to create arrays of words for each number of syllables.
//Since I am only looking for 5 and 7 syllable words now, I will only put those into arrays.
//In order to make it easy to expand for words of other syllable counts, I will use a switch statement rather than if/else
var syllCount5 = [];
var syllCount7 = [];
function syllNums(syllArray) {
for (i = 0, x = syllArray.length; i < x; i++) {
switch (syllArray[i]) {
case 5:
syllCount5.push(wordArray[i]);
break;
case 7:
syllCount7.push(wordArray[i]);
break;
}
}
}
//Now we will generate the random numbers that we will use to find the words we want
function getNum(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var fivesLength = syllCount5.length;
var sevensLength = syllCount7.length;
function writeHaiku(){
var x = getNum(0, fivesLength - 1);
var y = getNum(0, sevensLength - 1);
var z = getNum(0, fivesLength - 1);
console.log(syllCount5[x] + '\n' + syllCount7[y] + '\n' + syllCount5[z]);
}
Thanks!