【问题标题】:Chunk a sentence in to phrases with three words将一个句子分成三个单词的短语
【发布时间】:2020-10-08 03:24:21
【问题描述】:

如何将一个字符串分块成 3 个单词(或更少)的短语,并在末尾加上括号?

下面是一个示例字符串

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

以下是预期的结果

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

我添加了我的

这是我试过的

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

这也是我尝试过的,但它不起作用。

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

还有其他方法吗?

【问题讨论】:

  • 你如何确定一个短语?你试过什么?
  • 谁的头脑正常,两次点赞这篇帖子?
  • 嗨。我不确定如何确定短语。
  • 有没有办法确定词组?
  • 使用正则表达式:'This is a sample sentence containing some words with some other meanings.'.replace(/(\w+ \w+(?: \w+)?)/g,'[$1]')

标签: javascript


【解决方案1】:

好吧,这是一个简单的尝试:

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
}

【讨论】:

    猜你喜欢
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    相关资源
    最近更新 更多