JavaScript code to filter out common words in a string

后端 未结 6 1472
生来不讨喜
生来不讨喜 2020-12-15 12:20

I\'m trying to build JavaScript code that reads one string (say a sentence of English text), then outputs another string of (comma-separated) words that were \"uncommon\". S

6条回答
  •  遥遥无期
    2020-12-15 13:05

    Build an associative array of common words first, then tokenize sequence to output any words not contained in it. E.g.

    var excluded = new Object();
    common_words = common_words.split(",");
    for (var i in common_words) {
        excluded[common_words[i].trim().toLowerCase()] = true;
    }
    var result = new Array();
    var match = sentence.match(/\w+/g);
    for (var i in match) {
        if (!excluded[match[i].toLowerCase()]) {
            result.push(match[i]);
        }
    }
    var uncommon_words = result.join(", ");
    

提交回复
热议问题