回声页面上出现的前5个单词

时间:2018-11-15 19:33:35

标签: javascript php wordpress count word

是否有一个小功能或插件来获取页面上出现次数最多的5个单词?我正在建立一个具有动态内容的网站,我想检查大多数出现的相同词。

例如:页面上的“西班牙”一词大约12次,“荷兰”一词大约8次。我希望有一个功能可以自动检查并回显。

1 个答案:

答案 0 :(得分:1)

我不确定它会有用吗。您最终会得到毫无意义的单词。

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>