Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Word Statistics</title>
- <style>
- #txt {
- box-sizing: border-box;
- width: 100%;
- height: 45vh;
- }
- .controls {
- margin: .5rem 0;
- }
- .controls > *~* {
- margin-left: 2ex;
- }
- label, label input {
- cursor: pointer;
- }
- #out {
- margin-top: .3rem;
- }
- #out th {
- background-color: black;
- color: white;
- }
- #out td {
- background-color: #eee;
- }
- #out td:nth-child(2) {
- text-align: right;
- }
- </style>
- <script>
- var lst = [];
- function sortWord() {
- if (!lst.length) return;
- lst.sort((a, b) => {
- if (a[0] > b[0]) {
- return 1;
- } else return -1;
- });
- out.innerHTML = `<tr><th>Word</th><th>Count</th></tr>
- ${lst.map(v => `<tr><td>${v[0]}</td><td>${v[1]}</td>`).join("")}`;
- }
- function sortCount() {
- if (!lst.length) return;
- lst.sort((a, b) => {
- var c = b[1] - a[1];
- if (c) {
- return c;
- } else if (a[0] > b[0]) {
- return 1;
- } else return -1;
- });
- out.innerHTML = `<tr><th>Word</th><th>Count</th></tr>
- ${lst.map(v => `<tr><td>${v[0]}</td><td>${v[1]}</td>`).join("")}`;
- }
- function doAnalyze() {
- var rx = /\b(?:[a-z][a-z0-9]+(?:'[a-z]{1,2})?)\b/gi, l = {}, t = txt.value, c = 0, m, k;
- while (m = rx.exec(t)) {
- m = m[0].toLowerCase();
- if (m in l) {
- l[m]++;
- } else l[m] = 1;
- c++;
- }
- lst.length = 0;
- for (k in l) {
- lst.push([k, l[k]]);
- }
- count.textContent = c + " words found.";
- if (sw.checked) {
- sortWord();
- } else sortCount();
- }
- </script>
- </head>
- <body>
- <textarea id="txt"></textarea>
- <div class="controls">
- <button onclick="doAnalyze()">Analyze</button>
- <label for="sw"><input id="sw" name="sort" type="radio" onclick="sortWord()" />Sort By Word</label>
- <label for="sc"><input id="sc" name="sort" type="radio" checked onclick="sortCount()" />Sort By Count</label>
- <span id="count"></span>
- </div>
- <table id="out"></table>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement