繁体   English   中英

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

[英]Echo top 5 appearing words on page

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

例如,“西班牙”这个词在页面上出现了大约 12 次,而“荷兰”这个词出现了大约 8 次。 我想要一个功能来自动检查这个并回应这个。

我不确定它会有多大用处。 你最终会得到毫无意义的词。

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM