Advertisement
jcunews

WordStatistics.html

Apr 1st, 2019 (edited)
794
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 2.00 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5.   <title>Word Statistics</title>
  6.   <style>
  7. #txt {
  8.   box-sizing: border-box;
  9.   width: 100%;
  10.   height: 45vh;
  11. }
  12. .controls {
  13.   margin: .5rem 0;
  14. }
  15. .controls > *~* {
  16.   margin-left: 2ex;
  17. }
  18. label, label input {
  19.   cursor: pointer;
  20. }
  21. #out {
  22.   margin-top: .3rem;
  23. }
  24. #out th {
  25.   background-color: black;
  26.   color: white;
  27. }
  28. #out td {
  29.   background-color: #eee;
  30. }
  31. #out td:nth-child(2) {
  32.   text-align: right;
  33. }
  34.   </style>
  35.   <script>
  36. var lst = [];
  37. function sortWord() {
  38.   if (!lst.length) return;
  39.   lst.sort((a, b) => {
  40.     if (a[0] > b[0]) {
  41.       return 1;
  42.     } else return -1;
  43.   });
  44.   out.innerHTML = `<tr><th>Word</th><th>Count</th></tr>
  45. ${lst.map(v => `<tr><td>${v[0]}</td><td>${v[1]}</td>`).join("")}`;
  46. }
  47. function sortCount() {
  48.   if (!lst.length) return;
  49.   lst.sort((a, b) => {
  50.     var c = b[1] - a[1];
  51.     if (c) {
  52.       return c;
  53.     } else if (a[0] > b[0]) {
  54.       return 1;
  55.     } else return -1;
  56.   });
  57.   out.innerHTML = `<tr><th>Word</th><th>Count</th></tr>
  58. ${lst.map(v => `<tr><td>${v[0]}</td><td>${v[1]}</td>`).join("")}`;
  59. }
  60. function doAnalyze() {
  61.   var rx = /\b(?:[a-z][a-z0-9]+(?:'[a-z]{1,2})?)\b/gi, l = {}, t = txt.value, c = 0, m, k;
  62.   while (m = rx.exec(t)) {
  63.     m = m[0].toLowerCase();
  64.     if (m in l) {
  65.       l[m]++;
  66.     } else l[m] = 1;
  67.     c++;
  68.   }
  69.   lst.length = 0;
  70.   for (k in l) {
  71.     lst.push([k, l[k]]);
  72.   }
  73.   count.textContent = c + " words found.";
  74.   if (sw.checked) {
  75.     sortWord();
  76.   } else sortCount();
  77. }
  78.   </script>
  79. </head>
  80. <body>
  81.   <textarea id="txt"></textarea>
  82.   <div class="controls">
  83.     <button onclick="doAnalyze()">Analyze</button>
  84.     <label for="sw"><input id="sw" name="sort" type="radio" onclick="sortWord()" />Sort By Word</label>
  85.     <label for="sc"><input id="sc" name="sort" type="radio" checked onclick="sortCount()" />Sort By Count</label>
  86.     <span id="count"></span>
  87.   </div>
  88.   <table id="out"></table>
  89. </body>
  90. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement