This question already has answers here:
What is this Javascript “require”?
                            
                                (6个答案)
                            
                    
                5年前关闭。
        

    

我一直在尝试创建一个非常基本的Haiku Generator,它会从大型词典文件中解析文本,然后(至少目前)选择具有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]);
}


谢谢!

最佳答案

似乎您要在此处使用node,因此应使用以下命令从命令行运行此节点:

node <name_of_file>


这在Chrome上无法使用,因为node是服务器端平台,但Chrome控制台用于客户端。

关于javascript - Haiku Generator-如何运行此脚本? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25316254/

10-09 23:49