我想从千行读取一个大文件。每行都有单词和短语。
所以如果文件是这样的:
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(",")
期望的结果修改:
key, phrase, combination of words, phrase
phrase, word
key, words, phrase, combination of keys
words, phrase, combination of keys
答案 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
来读取文件的每一行,然后使用简单的算法循环显示单词并将其添加到将添加到输出文件的字符串中。