我一直在尝试创建一个非常的 basic Haiku生成器,它解析大字典文件中的文本,然后(至少现在)选择有5个或7个音节的单词并输出它们。
下面是我第一次使用这段代码,但我现在遇到的问题是,我不知道如何测试或运行这段代码。当我把它放到Chrome控制台时,我会得到一个错误“”,这是解析数据的代码的一个组成部分,所以我不知道如何解决这个问题。有人能对此提供一些见解吗?
这是我的密码:
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]);
}谢谢!
发布于 2014-08-14 19:41:32
看起来您在这里尝试使用节点,因此您应该在命令行中使用以下命令运行该节点:
node <name_of_file>这在Chrome上是行不通的,因为节点是一个服务器端平台,但Chrome控制台是用于客户端的。
https://stackoverflow.com/questions/25316254
复制相似问题