我一直在尝试创建一个非常非常的基本Haiku生成器,它解析大型字典文件中的文本然后(至少现在)选择具有5或7个音节的单词并输出它们。
下面是我第一次使用代码,但我现在遇到的问题是我不知道如何测试或运行此代码。当我通过我的Chrome JS控制台时,我收到错误"要求未定义",这是解析数据的代码的组成部分,因此我不确定如何修复这个。任何人都可以对此提供一些见解吗?
这是我的代码:
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]);
}
谢谢!
答案 0 :(得分:0)
看起来您正在尝试在此处使用节点,因此您应该使用以下命令从命令行运行此命令:
node <name_of_file>
这无法在Chrome上运行,因为node是服务器端平台,但Chrome控制台是用于客户端的。