[英]node.js read a text file and write modify strings. (each line has a word order)
I would like to read a large file from a thousand lines. 我想从一千行中读取一个大文件。 Each line has the words and phrases. 每行都有单词和短语。
So if the file is like this: 因此,如果文件是这样的:
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
In line combination or single words separated by commas 行组合或单个单词用逗号分隔
.split(",")
Desired result modify: 所需结果修改:
key, phrase, combination of words, phrase
phrase, word
key, words, phrase, combination of keys
words, phrase, combination of keys
Here is a sample doing what you asked : 这是按照您的要求进行操作的样本:
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)
});
You can use readline
from npm to read each line of the file, and then with a simple algorithm, loop over the words and add them to a string that will be added to the output file. 您可以使用npm中的readline
读取文件的每一行,然后使用简单的算法遍历单词并将其添加到将添加到输出文件的字符串中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.