【问题标题】:What's the best way to count keywords in JavaScript?在 JavaScript 中计算关键字的最佳方法是什么?
【发布时间】:2010-09-13 13:35:36
【问题描述】:

在 JavaScript 中计算关键字的最佳和最有效的方法是什么?基本上,我想取一个字符串,得到字符串中出现的前N个单词或短语,主要是为了提示标签的使用。我正在寻找更多的概念提示或现实生活示例的链接,而不是实际代码,但我当然不介意您是否也想共享代码。如果有特定的功能会有所帮助,我也将不胜感激。

现在我想我正在使用 split() 函数用空格分隔字符串,然后用正则表达式清除标点符号。我还希望它不区分大小写。

【问题讨论】:

    标签: javascript regex arrays string


    【解决方案1】:

    尝试按单词拆分字符串并计算结果单词,然后按计数排序。

    【讨论】:

      【解决方案2】:

      一旦你清理了那组单词,假设你称之为wordArray

      var keywordRegistry = {};
      
      for(var i = 0; i < wordArray.length; i++) {
         if(keywordRegistry.hasOwnProperty(wordArray[i]) == false) {
            keywordRegistry[wordArray[i]] = 0;
         }
         keywordRegistry[wordArray[i]] = keywordRegistry[wordArray[i]] + 1;
      }
      
      // now keywordRegistry will have, as properties, all of the 
      // words in your word array with their respective counts 
      
      // this will alert (choose something better than alert) all words and their counts
      for(var keyword in keywordRegistry) {
        alert("The keyword '" + keyword + "' occurred " + keywordRegistry[keyword] + " times");
      }
      

      这应该会给你做这部分工作的基础知识。

      【讨论】:

      • 当然 - 我会花时间发布完整的解决方案,但我还有工作要做,需要得到报酬! :) 此外,无论如何,这对我来说是最有趣的部分(这真的没那么有趣)——其余的都很简单。
      【解决方案3】:

      剪切、粘贴+执行演示:

      var text = "Text to be examined to determine which n words are used the most";
      
      // Find 'em!
      var wordRegExp = /\w+(?:'\w{1,2})?/g;
      var words = {};
      var matches;
      while ((matches = wordRegExp.exec(text)) != null)
      {
          var word = matches[0].toLowerCase();
          if (typeof words[word] == "undefined")
          {
              words[word] = 1;
          }
          else
          {
              words[word]++;
          }
      }
      
      // Sort 'em!
      var wordList = [];
      for (var word in words)
      {
          if (words.hasOwnProperty(word))
          {
              wordList.push([word, words[word]]);
          }
      }
      wordList.sort(function(a, b) { return b[1] - a[1]; });
      
      // Come back any time, straaanger!
      var n = 10;
      var message = ["The top " + n + " words are:"];
      for (var i = 0; i < n; i++)
      {
          message.push(wordList[i][0] + " - " + wordList[i][1] + " occurance" +
                       (wordList[i][1] == 1 ? "" : "s"));
      }
      alert(message.join("\n"));
      

      可复用功能:

      function getTopNWords(text, n)
      {
          var wordRegExp = /\w+(?:'\w{1,2})?/g;
          var words = {};
          var matches;
          while ((matches = wordRegExp.exec(text)) != null)
          {
              var word = matches[0].toLowerCase();
              if (typeof words[word] == "undefined")
              {
                  words[word] = 1;
              }
              else
              {
                  words[word]++;
              }
          }
      
          var wordList = [];
          for (var word in words)
          {
              if (words.hasOwnProperty(word))
              {
                  wordList.push([word, words[word]]);
              }
          }
          wordList.sort(function(a, b) { return b[1] - a[1]; });
      
          var topWords = [];
          for (var i = 0; i < n; i++)
          {
              topWords.push(wordList[i][0]);
          }
          return topWords;
      }
      

      【讨论】:

      • 该死,你的空闲时间肯定比我多!我可以寄给你一些工作吗? ;) J/K 只是让你很难过,因为你基本上给了这个家伙完整的工作代码,而不是一些零碎的代码(就像我做的那样)。让他自己想出某事
      • 只花了几分钟。比应有的时间长了几分钟,因为我正在“在黑暗中安静地坐着,听听孩子在隔壁房间醒来”的职责,所以我一直打错:)
      • @insin 哇,谢谢。比我预期的要多得多,但它将作为一个很好的参考点。 @Jason 我正在编写一个带有更多选项的 MooTools 类,所以还有一些工作要做。不过,insin 确实有帮助。
      【解决方案4】:

      我会完全按照您上面提到的方法来隔离每个单词。然后我可能会将每个单词添加为数组的索引,并将出现次数作为值。

      例如:

      var a = new Array;
      a[word] = a[word]?a[word]+1:1;
      

      现在您知道有多少个唯一单词 (a.length) 以及每个单词出现了多少次 (a[word])。

      【讨论】:

      • 这行不通——您实际上是在将数组用作对象,而不是数组。像这样向数组添加属性只会在属性为数字时更新数组的报告长度。
      【解决方案5】:

      这建立在 insin 之前的回答之上,只有一个循环:

      function top_words(text, n) {
          // Split text on non word characters
          var words = text.toLowerCase().split(/\W+/)
          var positions = new Array()
          var word_counts = new Array()
          for (var i=0; i<words.length; i++) {
              var word = words[i]
              if (!word) {
                  continue
              }
      
              if (typeof positions[word] == 'undefined') {
                  positions[word] = word_counts.length
                  word_counts.push([word, 1])
              } else {
                  word_counts[positions[word]][1]++
              }
          }
          // Put most frequent words at the beginning.
          word_counts.sort(function (a, b) {return b[1] - a[1]})
          // Return the first n items
          return word_counts.slice(0, n)
      }
      
      // Let's see if it works.
      var text = "Words in here are repeated. Are repeated, repeated!"
      alert(top_words(text, 3))
      

      例子的结果是:[['repeated',3], ['are',2], ['words', 1]]

      【讨论】:

        猜你喜欢
        • 2010-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多