javascript - 如何不显示字符串中只出现一次的短语?

标签 javascript string

我的函数遍历文本中的短语并显示在文本中至少出现一次的所有短语。我没有找到一种方法来不显示在文本中只出现一次的短语。

function toPhrases(text, wordCount) {
    const words = text.match(/[\w\u0402-\u045f]+/ig)
    const phrases = new Map()
    for (let i = 0; i < words.length; i++) {
        let phrase = words.slice(i, i + wordCount).join(' ')
        let hashedPhrases = phrases.get(phrase)
        if (hashedPhrases) {
            phrases.set(phrase, hashedPhrases + 1)
        } else {
            phrases.set(phrase, 1)
        }
        if (i + wordCount >= words.length) {
            break
        }
    }
    return phrases
}

function createPhrases() {
    const text = document.getElementById('textarea').value;
    document.getElementById('output-2').innerHTML = JSON.stringify([...toPhrases(text.toString(), 2)]);
    document.getElementById('output-3').innerHTML = JSON.stringify([...toPhrases(text.toString(), 3)]);
    document.getElementById('output-4').innerHTML = JSON.stringify([...toPhrases(text.toString(), 4)]);
}

最佳答案

这应该有效:

function toPhrases(text, wordCount){
  const words = text.match(/[\w\u0402-\u045f]+/ig)

  const groups = words.reduce((acc, w) => {
    acc[w] = (acc[w] + 1) || 1;
    return acc;
  }, {});

  // group is an object where keys are all the words and values are the occurrence of that word


  // now filter to get all the words that has only one occurrence
  return Object.keys(groups).filter(k => groups[k] === 1)

}

关于javascript - 如何不显示字符串中只出现一次的短语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59499938/

相关文章:

php - 如何在 PHP 中将两个字符串组合在一起?

java - 如何从其他生成的等效字符串中获取字符串值

javascript - 更改 jQueryUI 选项卡标题

javascript - jquery 脚本 : z-index and setTimeout 的两个问题

javascript - Laravel 5 中有 2 个日期选择器,但仅保存最后一个值

python - 根据用户输入替换列表中的项目

javascript - 如何在没有 jQuery 或 bootstrap.js javascript 的情况下打开 Bootstrap 模式?

javascript - css 中 java window.pack() 的等价物

javascript - 在任何地方替换字符串,除非它在引号内

r - 如果字符串包含 x 在 R 中做 y