node.js读取文本文件并编写修改字符串。 (每行都有一个单词顺序)

时间:2016-05-22 16:04:18

标签: javascript node.js

我想从千行读取一个大文件。每行都有单词和短语。

所以如果文件是这样的:

key, phrase, combination of words, phrase, combination of keys, word
phrase, word
key, words, phrase, combination of keys, combination of words
combination of keys
words, phrase, combination of keys

用逗号分隔的行组合或单个单词

.split(",")
  1. 如何在字符串中写入前四个字或更少字的组合文件?
  2. 如何在没有逗号的情况下写入文件字符串?
  3. 期望的结果修改:

    key, phrase, combination of words, phrase
    phrase, word
    key, words, phrase, combination of keys
    words, phrase, combination of keys
    

1 个答案:

答案 0 :(得分:0)

这是一个做你所问的样本:

var fs = require('fs');
var output;
var lineReader = require('readline').createInterface({
    input: fs.createReadStream(__dirname + '/file')
});

var output = fs.createWriteStream(__dirname + '/output.txt');


lineReader.on('line', function (line) {
    var array = line.split(',');
    var toWrite = "";

    if (array.length <= 4) {
        for (var i = 0 ; i < array.length ; i++) {
            toWrite += array[i] + ",";
        }
    } else {
        for (var i = 0 ; i < 4 ; i++) {
            toWrite += array[i] + ",";
        }
    }

    toWrite = toWrite.slice(0,-1);
    toWrite += "\r\n";

    output.write(toWrite)

});

您可以使用npm中的readline来读取文件的每一行,然后使用简单的算法循环显示单词并将其添加到将添加到输出文件的字符串中。