从文本文件中打印随机数量的单词

时间:2019-05-21 17:32:36

标签: node.js

我有一个包含100个单词的文本文件。我希望我的程序从要打印的文本文件中的100个单词中选择1到7之间的随机单词。

我知道如何获得随机数

var ranNum = Math.floor(Math.random() * 7) +1 ; 

但不确定如何让我的程序选择ranNum确定的随机单词数量

function randomWord(){

   var fs = require('fs');

   var readME = fs.readFileSync('text.txt', 'utf8', function(err,data) { 
      //reads text file 
      console.log(data);
   });
   console.log(readME);

   //returns a random num between 1-9 
   var ranNum = Math.floor(Math.random() * 7) + 1;  
   console.log(ranNum); //prints out that number

 }

 randomWord();

我希望程序每次运行时都从文本文件中随机选择一个单词

1 个答案:

答案 0 :(得分:2)

如果您想从文本文件中获取n个随机单词,并且该文本文件包含这样的字符串:

apple, orange, banana, pear, elephant, horse, dog, cow, brazil, england, france

您可以使用以下代码:

// declare 'require()' imports at the top of your script
var fs = require('fs');

function randomWords(words){
    // Since you use 'readFileSync', there is no callback function
    var readME = fs.readFileSync('text.txt', 'utf8');

    // Split the string into an array
    var wordArr = readME.split(', ');

    // Check if the specified amount of words is bigger than
    // the actual array length (word count) so we don't end 
    // up in an infinite loop 
    words = words > wordArr.length ? wordArr.length : words;

    // Create empty array
    var randWords = [];

    // push a random word to the new array n times
    for (let i = 0; i < words; i++){

        // new random number
        let newRandom;
        do {
            // New random index based on the length of the array (word count)
            let rand = Math.floor(Math.random() * wordArr.length);
            newRandom = wordArr[rand];
        }
        // Make sure we don't have duplicates
        while (randWords.includes(newRandom));

        // Add the new word to the array
        randWords.push(newRandom);
    }

    // Join the array to a string and return it
    return randWords.join(', ');
}

// You can pass the amount of words you want to the function
console.log(randomWords(5));

我评论了代码以进行澄清。


工作代表演示: Demo