简体   繁体   中英

Chunk a sentence in to phrases with three words

How to chunk a string in to 3-word(or less) phrases with brackets at ends?

Following is a sample string

This is a sample sentence containing some words with some other meanings.

Following is the expected result

[This is a sample] [sentence containing some] [words with some] [other meanings.]

I've added mine

this is what i've tried

    this.mod = this.data.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|");
    this.mod.map((sentence) => {
      sentence.split(' ').reduce((acc, cur, idx, arr) => {
        acc + cur
      } ,'')
    })

This is also what I've tried & it is not working.

    const res = this.mod.map((sentence) => {
      return sentence.split(" ").reduce((acc, cur, idx, arr) => {
        acc + (idx % 3 === 0) ? `][${cur}]` : cur;
      }, "[");
    });

Is there any other approach?

Ok here is a simple stab at it:

function chunkIt(str) {
  const words = str.split(' ') // split into individual words
  const result = []
  let phrase = []
  for (const word of words) {
    if (phrase.length < 3) {
      phrase.push(word)
    }

    if (phrase.length === 3) {
      result.push(phrase.join(' '))
      phrase = [] 
    }
  }  
  if (phrase.length > 0) {
    result.push(phrase.join(' '))
  }
  return result
}

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