Domanda

Qual è il modo migliore ed efficiente per contare le parole chiave in JavaScript? Fondamentalmente, mi piacerebbe prendere una stringa e ottenere le prime N parole o frasi che compaiono nella stringa, principalmente per l'uso di suggerimenti di tag. Sto cercando più suggerimenti concettuali o collegamenti ad esempi di vita reale rispetto al codice reale, ma certamente non mi dispiacerebbe se ti piacerebbe condividere anche il codice. Se ci sono funzioni particolari che potrebbero aiutare, lo apprezzerei anche.

In questo momento penso di usare la funzione split () per separare la stringa per spazi e quindi pulire la punteggiatura con un'espressione regolare. Vorrei anche che non distingue tra maiuscole e minuscole.

È stato utile?

Soluzione

Taglia, incolla + esegui demo:

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"));

Funzione riutilizzabile:

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

Altri suggerimenti

Dopo aver ripulito quell'array di parole e diciamo che lo chiami 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");
}

Questo dovrebbe darti le basi per fare questa parte del lavoro.

Prova a dividere la stringa di parole e conta le parole risultanti, quindi ordina i conteggi.

Questo si basa su una precedente risposta di insin con un solo ciclo:

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))

Il risultato dell'esempio è: [['ripetuto', 3], ['sono', 2], ['parole', 1]]

Farei esattamente ciò che hai menzionato sopra per isolare ogni parola. Vorrei quindi aggiungere ogni parola come indice di un array con il numero di occorrenze come valore.

Ad esempio:

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

Ora sai quante parole uniche ci sono (a.length) e quante occorrenze di ogni parola esistevano (una [parola]).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top