Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into pairs, triplets, quadruplets and on (ngrams)?

I would like to split natural text into word pairs, triplets, quadruplets and on!

I have figured out how to split into pairs so far. I assume I will need an additional loop to accommodate the word count

Here is the code for pairs

var test = "I love you so much, but Joe said \"he doesn't\"!";
var words = test.split(" ");
var two_words = [];
for (var i = 0; i < words.length - 1; i++) {
  two_words.push(words[i] + ' ' + words[i + 1]);
}
console.log(two_words);

// Here is what I am trying

var words = test.split(" ");
var split_words = [];
var split_length = 5;
for (var l = 2; l <= split_length; l++) {
  for (var i = 0; i < words.length - (l - 1); i++) {
    var split_word;
    for (c = 0; c <= l; c++) {
      split_word += split_words[i + c];
    }
    split_words.push(split_word);
  }
}

console.log(split_words);

Adding expected output...(an array of ngrams) sg like this

// 2grams
"I love"
"love you"
"you so"
"so much,"
"much, but"
"but Joe"
"Joe said"
"said "he"
""he doesn't"!"
//3grams
"I love you"
"love you so"
"you so much"
"so much, but"
//and on and on
like image 887
giorgio79 Avatar asked Dec 05 '25 14:12

giorgio79


2 Answers

This is called "n-grams" and can be done in modern JavaScript using generators like this:

function* ngrams(a, n) { 
    let buf = [];

    for (let x of a) {
        buf.push(x);
        if (buf.length === n) {
            yield buf;
            buf.shift();
        }
    }
}


var test = "The quick brown fox jumps over the lazy dog";

for (let g of ngrams(test.split(' '), 3))
    console.log(g.join(' '))

Another, more concise and probably faster option:

let ngrams = (a, n) => a.slice(0, 1 - n).map((_, i) => a.slice(i, i + n));
like image 132
georg Avatar answered Dec 08 '25 03:12

georg


Assuming that your desired result does not include jumbled ordered combinations, you can try following

// Code goes here

var test = "I love you so much, but Joe said \"he doesn't\"!";
var arr = test.split(" ");


var words = arr.length; // total length of words
var result = [];

function process(arr, length) { // process array for number of words
  var temp = [];
  // use equal if want to include the complete string as well in the array
  if (arr.length >= length) { 
    // the check excludes any left over words which do not meet the length criteria 
    for (var i = 0; (i + length) <= arr.length; i++) { 
      temp.push(arr.slice(i, length + i).join(" "));
    }

    result.push(temp);
    process(arr, length + 1); // recursive calling
  }

}

process(arr, 2);

console.log(result);
like image 40
Nikhil Aggarwal Avatar answered Dec 08 '25 04:12

Nikhil Aggarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!