簡體   English   中英

如何獲取並顯示對象中每個單詞的計數?

[英]How do I get and display the count of each word from an object?

如何獲取並顯示字符串中每個單詞的計數?

我可以對最常用的單詞進行排序,但無法顯示計數。 對象:頻率最初顯示計數(鍵)。

我知道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);

我個人有幾件事會做不同的事情。 如果將排除項保存在單獨的數組中,則可能更容易閱讀和更新。 此外,您無需為它們進行正則表達式,只需使用filter即可
至於打印結果,一個簡單的for..in循環就可以了。

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

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

使用本文中的一些代碼:

 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); 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" /> <div class="container"> <div class="row justify-content-center"> <div class="col-sm-10 col-md-8"> <table class='table table-striped'> <thead class='thead-inverse'> <tr> <th>Word</th> <th>Count</th> </tr> </thead> <tbody id="wordlist"></tbody> </table> </div> </div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM