在JavaScript中计算关键字的最佳方法是什么?

时间:2008-09-26 18:59:15

标签: javascript regex arrays string

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

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

5 个答案:

答案 0 :(得分:4)

一旦你清理了这一系列的单词,让我们称之为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");
}

这应该为您提供完成这部分工作的基础知识。

答案 1 :(得分:4)

剪切,粘贴+执行演示:

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;
}

答案 2 :(得分:1)

尝试将字符串拆分为单词并计算生成的单词,然后对计数进行排序。

答案 3 :(得分:1)

这建立在 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]]

答案 4 :(得分:-1)

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

例如:

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

现在您知道有多少独特单词(a.length)以及每个单词出现的次数([word])。