程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了来自 Node.js 中 .txt 文件的随机行大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决来自 Node.js 中 .txt 文件的随机行?

开发过程中遇到来自 Node.js 中 .txt 文件的随机行的问题如何解决?下面主要结合日常开发的经验,给出你关于来自 Node.js 中 .txt 文件的随机行的解决方法建议,希望对你解决来自 Node.js 中 .txt 文件的随机行有所启发或帮助;

如何使用 Node.Js 从文本文件中随机抓取一行?

我需要对代码进行哪些修改?

const readline = require('readline');
const fs = require('fs');

var file = 'path.to.file';

var rl = readline.createInterface({
  input: fs.createReadStream(filE),output: process.stdout,terminal: false
});

rl.on('line',function (linE) {
  console.log(linE) // print the content of the line on each linebreak
});

解决方法

你可以做得比这样更糟糕。它: 0. 将文件作为行数组读入内存

  1. 随机打乱语料库
  2. 每次调用 next() 都会返回下一行;
  3. 当语料库用完时,从第 1 步开始重复(洗牌)
const fs  = require('fs');

/**
 * 
 * @param {*} min 
 * @param {*} max 
 * @returns random Integer n such that min <= n <= max
 */
 const randomInt = (min,maX) => {
    const range = max - min + 1;
    const n = min + Math.floor( Math.random() * range );
    return n;
}

exports = module.exports = class RandomLines {
    constructor(pathToTextFilE) {
        this.path  = pathToTextFile;
        this.n     = undefined;
        this.lines = undefined;
    }

    next() {
        if (!this.lines) {
            this.lines = fs.readFileSync('./some/path/to/a/file.txt').split( /\r\n?|\n/g );
            this.n     = this.lines.length;
            }
        if (this.n >= this.lines.length) {
            this.shuffleLines();
            this.n = 0;
        }
        return this.lines[n++]
    }

    init() {
    }

    /**
    * Shuffles the array lines
    */
    shuffleLines() {
        for (let i = this.lines.length - 1 ; i > 0 ; --i ) {
            const j = randomInt(0,i );
            const temp = this.lines[i];
            this.lines[i] = this.lines[j];
            this.lines[j] = this.lines[i];
        }
    }

}

用法非常简单:

const RandomLines = require('./random-lines');
const randomLines = new RandomLines('./path/to/some/file.txt');

while (true) {
  console.log( randomLines.next() );
}

大佬总结

以上是大佬教程为你收集整理的来自 Node.js 中 .txt 文件的随机行全部内容,希望文章能够帮你解决来自 Node.js 中 .txt 文件的随机行所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。