Эхо топ 5 появляющихся слов на странице - PullRequest
0 голосов
/ 15 ноября 2018

Есть ли небольшая функция или плагин, чтобы получить 5 самых популярных слов на странице?Я создаю веб-сайт с динамическим контентом, и я хочу проверить наличие наиболее часто встречающихся слов.

Например: слово «Испания» присутствует на странице около 12 раз, а слово «Нидерланды» - около 8раз.Я хочу иметь функцию, чтобы проверить это автоматически и повторить это.

1 Ответ

0 голосов
/ 15 ноября 2018

Я не уверен, насколько это было бы полезно. Вы в конечном итоге с бессмысленными словами.

let text = document.querySelector('#input').innerText.split(/\s/);
let counts = text.map(w => w.toLowerCase()).reduce((acc, cv) => {
  if (cv.length > 0)
    acc[cv] = acc[cv] + 1 || 1;
  return acc;
}, {});
text = Object.keys(counts).sort((a, b) => counts[b] - counts[a]).slice(0, 5);
console.log(text);
<div id="input">
  <p>
    Is there a little function or plugin to get the top 5 most appearing words on a page? I am building a website with dynamic content and I want to check for most appearing same words.
  </p>
  <p>
    For example: The word 'Spain' is on the page for around 12 times and the word 'Netherlands' for around 8 times. I want to have a function to check this automatically and echo this.
  </p>
</div>

Добавлена ​​фильтрация

Мы можем отфильтровать массив перед подсчетом слов, поэтому вы можете добавить все, что вам нравится, в массив filters, чтобы избавиться от этих слов. Я, наверное, должен был подумать об этом для начала ...

const filters = ['a', 'to', 'the', 'for', 'i'];
let text = document.querySelector('#input').innerText.split(/\s/);
let counts = text.map(w => w.toLowerCase()).filter(w => !filters.includes(w)).reduce((acc, cv) => {
  if (cv.length > 0)
    acc[cv] = acc[cv] + 1 || 1;
  return acc;
}, {});
text = Object.keys(counts).sort((a, b) => counts[b] - counts[a]).slice(0, 5);
console.log(text);
<div id="input">
  <p>
    Is there a little function or plugin to get the top 5 most appearing words on a page? I am building a website with dynamic content and I want to check for most appearing same words.
  </p>
  <p>
    For example: The word 'Spain' is on the page for around 12 times and the word 'Netherlands' for around 8 times. I want to have a function to check this automatically and echo this.
  </p>
</div>
...