遇到的一个问题,一偏英文文章要统计单词数量,以做热力图,以前是用php解决的,现在觉得用服务端资源非常奢侈,直接在前端完成,不占服务器资源。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>projectname</title>
</head>
<body>
<div id="app"></div>
<script>
let article = 'In my dual profession as an educator and health care provider, I have worked with numerous children infected with the virus that causes AIDS. The relationships that I have had with these special kids have been gifts in my life. They have taught me so many things, but I have especially learned that great courage can be found in the smallest of packages. Let me tell you about Tyler.'
let arry = article.split(' ')
const words = arry.length // 单词个数
arry = arry.map(word => word.replace(/\,|\.|\"|\'|\!/g, '')) // 替换单词中的符号
// 统计重复单词个数
const wordObj = []
let count = 0
for (let i = 0, len = arry.length; i < len; i++) {
// 如果这个单词已经存在则跳过
if (wordObj[arry[i]]) {
continue
}
for (let j = 0; j < len; j++) {
if (arry[i] === arry[j]) {
count++
}
}
wordObj[arry[i]] = count
count = 0
}
const news = []
let const1 = 0
for (key in wordObj) {
news[const1] = {name:key,num:wordObj[key]}
const1++
}
const1 = 0
function sortId(a,b){
return b.num-a.num
}
news.sort(sortId);
console.log(news);
</script>
</body>
</html>