简体   繁体   中英

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(",")
  1. How to write to file the combination of the first four words or less in string?
  2. How not to write to file strings without commas?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM