Node.js 从文本文件中打印任意数量的单词
我有一个包含100个单词的文本文件。我希望我的程序从文本文件中的100个单词中随机选择1-7个单词进行打印 我知道如何得到一个随机数Node.js 从文本文件中打印任意数量的单词,node.js,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',
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();
如果要从文本文件中获取
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));
//在脚本顶部声明'require()'导入
var fs=需要('fs');
虚词{
//由于使用了“readFileSync”,因此没有回调函数
var readME=fs.readFileSync('text.txt','utf8');
//将字符串拆分为数组
var-wordArr=readME.split(',');
//检查指定的字数是否大于
//实际数组长度(字数),因此我们不结束
//无限循环
单词=单词>单词长度?单词长度:单词;
//创建空数组
var randWords=[];
//将随机字推送到新数组n次
for(设i=0;i
我对代码进行了注释以进行澄清
正在工作的Repl.it演示:那么文件中的单词是如何排列的?@epascarello纯文本:苹果、橘子、香蕉、梨、大象、马、狗、牛、巴西、英国、,france@NullDev对于每一次迭代,我希望有一个1到7个单词之间的随机数量谢谢!我刚刚试过,但现在意识到ranNum从前7个单词中挑选了randon Num。我的意思是这个列表有100个单词,我想让程序从整个列表中随机挑选7个单词。问题是,它不是一个随机的集合。非常感谢!