如何获取并显示对象中每个单词的计数?

时间:2017-10-07 22:12:16

标签: javascript html5

如何获取并显示字符串中每个单词的计数?

我能够对最频繁的单词进行排序,但我无法显示计数。对象:频率最初显示计数(键)。

我理解Object.keys和map()方法可能对我有帮助,但我不确定如何在我的代码中包含map方法。

非常感谢任何帮助...

var stringtest = "Example: This is a string. I've excluded stopwords from becoming most frequent words. This is a string of words.";
    function getFreq(string, cutOff){
      var refineStr = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").toLowerCase().replace(/ to\b| is\b| for\b| you\b| the\b|your\b|an\b| on\b| by\b|this\b|will\b| of\b| a\b/g, ""),
          words = refineStr.split(" "),
          frequencies = {},
          word, frequency, i;
      for(i = 0; i < words.length; i++){
        word = words[i];
        frequencies[" " + words[i]] = (frequencies[" " + words[i]] || 0) + 1;
        //frequencies[word]++;
      }
      words = Object.keys(frequencies);
         return words.sort(function (a,b)
          {
            return frequencies[b] - frequencies[a];}).slice(0, cutOff).toString();
    }
    document.getElementById("wordlist").innerHTML = getFreq(stringtest, 20);

3 个答案:

答案 0 :(得分:1)

我个人会做一些不同的事情。如果将排除项保存在单独的数组中,则读取和更新可能会更容易。此外,您不需要为他们使用正则表达式,您只需使用filter 至于打印结果,一个简单的for..in循环就可以了。

&#13;
&#13;
const write = msg => {
  document.body.appendChild(document.createElement('div')).innerHTML = msg;
};

const input = "Example: This is a string. I've excluded stopwords from becoming most frequent words. This is a string of words.";
const exclude = ["to", "is", "for", "you", "the", "your", "an", "on", "by", "this", "will", "of", "a"];

const lowerAlphaNum = input.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g, "").toLowerCase();
const filtered = lowerAlphaNum.split(" ").filter(word => exclude.indexOf(word) === -1);
const frequencies = {};
filtered.forEach(word => {
  frequencies[word] = (frequencies[word] || 0) + 1;
});

const sortedArr = Object.keys(frequencies).map(word => ({
  word: word,
  frequency: frequencies[word]
})).sort((a, b) => b.frequency - a.frequency);
const trimmedArr = sortedArr.slice(0, 5);

trimmedArr.forEach(item => {
  write(item.word + ': ' + item.frequency);
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

"use strict";

let test = 'Example: This is a string. I\'ve excluded stop words from becoming most frequent words. This is a string of words.';
test = test.replace(/[.,:]/g, '');
test = test.replace(/ to\b| is\b| for\b| you\b| the\b|your\b|an\b| on\b| by\b|this\b|will\b| of\b| a\b/g, "");
test = test.split(' ');

let obj = {};

for (let i = 0, max = test.length; i < max; i++) {
    if (!obj.hasOwnProperty([test[i]])) {
        obj[test[i]] = 1;
        continue;
    }

    obj[test[i]]++;
}

displayResult(obj, 30);

function displayResult(obj, maxAmount) {
    let keys = Object.keys(obj);
    let ul = document.createElement('ul');

    if (maxAmount > keys.length) {
        maxAmount = keys.length;
    }

    for (let i = 0; i < maxAmount; i++) {

        let li = document.createElement('li');

        li.innerHTML = keys[i] + ' : ' + obj[keys[i]];
        ul.appendChild(li);
    }

    document.querySelector('#wordlist').appendChild(ul);
}
<div id="wordlist"></div>

答案 2 :(得分:0)

使用this article中的一些代码:

&#13;
&#13;
collectionView?.collectionViewLayout = layout
&#13;
var stringtest =
  "Example: This is a string. I've excluded stopwords from becoming most frequent words. This is a string of words.";

function stringCount(string) {
  var pattern = /(?=\S*['-])([a-zA-Z'-]+)|\w+/g,
    matchedWords = string.match(pattern);

  var counts = matchedWords.reduce(function(stats, word) {
    if (stats.hasOwnProperty(word)) {
      stats[word] = stats[word] + 1;
    } else {
      stats[word] = 1;
    }
    return stats;
  }, {});

  Object.keys(counts).map(function(key, index) {
    document.getElementById("wordlist").innerHTML +=
      `<tr>
       <td>${key}</td>
       <td>${counts[key]}</td>
     </tr>`;
  });
}

stringCount(stringtest);
&#13;
&#13;
&#13;