首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何不显示一个在字符串中只出现一次的短语?

如何不显示一个在字符串中只出现一次的短语?
EN

Stack Overflow用户
提问于 2019-12-27 19:13:41
回答 2查看 55关注 0票数 0

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

代码语言:javascript
复制
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)]);
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-12-27 19:37:26

您可以像这样按短语计数过滤结果:

代码语言:javascript
复制
const thing = "do the thing that is the thing that you do";
console.log([...toPhrases(thing, 2)]);

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(' '),
      hashedPhrases = phrases.get(phrase);
    if (hashedPhrases) { phrases.set(phrase, hashedPhrases + 1); }
    else { phrases.set(phrase, 1); }
    if (i + wordCount >= words.length) { break; }
  }
  // Each member of phrases is actually a two-element array like [phrase, count], so...
  let duplicatePhrases = [...phrases].filter(phrase => phrase[1] > 1);
  return duplicatePhrases;
}

票数 0
EN

Stack Overflow用户

发布于 2019-12-27 19:26:25

这应该是可行的:

代码语言:javascript
复制
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)

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59499938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档