2

我想创建一个小书签来计算网页上的所有文本,然后在绝对定位的 div 中显示从最多到最少的结果。

我所做的每个谷歌搜索都在谈论计算表单或文本区域或已知 div id 中的单词总数。那不是我想要的。我想要每个 /w 出现在整个网页上的次数。

我知道足够多的 javascript 知道我不知道如何做到这一点。

4

1 回答 1

2

像这样的东西应该工作:

function countWordFrequency() {
  var freq={};
  // Traverse the DOM looking for text nodes.
  recurseTextNodes(function(textNode) {
    // Split the text into words, removing punctuation.
    var words = textNode.data.replace(/[^\w\s]/g, '').split(/\s+/)
      , len = words.length;
    // Count the word frequency.
    for (var i=0; i<len; i++) {
      // if (freq[words[i]]) { bug if one of the words is "constructor"!
      if (typeof freq[words[i]] === 'number') {
        freq[words[i]] += 1;
      } else  {
        freq[words[i]] = 1;
      }
    }
  });
  return freq;
}

这个解决方案在删除标点符号和解析单词的方式上可能过于简单,但应该展示这个想法。该recurseTextNodes功能也留给读者作为练习=)。如何将此例程存储为书签也有影响(尤其是如何向最终用户显示结果),但我再次假设您已经知道如何做到这一点。

于 2010-08-13T18:59:56.293 回答