1 回答
TA贡献1836条经验 获得超5个赞
要获得@SimoneRossaini所说的单词密度,只需使用列表并保存找到每个单词的次数即可。例如,这最终是这样的:
我修改了您的代码并添加了“密度”一词。
const displayText = () => {
const inputPage = document.getElementById("input-page");
const countPage = document.getElementById("count-page");
const text = document.getElementById("text");
const textValue = text.value;
if (text.value !== "") { // normal flow will continue if the text-area is not empty
inputPage.style.display = "none";
document.getElementById("display-text").innerText = textValue;
countPage.style.display = "block";
} else { // if the text-area is empty, it will issue a warning.
alert("Please enter some text first.")
}
const countWords = (str) => {
return str.split(" ").length;
};
const wordCount = (countWords(textValue));
const renderWordCount = () => {
const wordCountDiv = document.getElementById("word-count");
wordCountDiv.innerHTML = "<h1> Words Counted: " + wordCount + "</h1>";
};
const getWordDensity = (str) => {
let wordList = {};
str.split(/[\s\.,]+/).forEach(word => {
if(typeof wordList[word] == "undefined"){
wordList[word] = 1;
}
else{
wordList[word]++;
}
});
return wordList;
};
const wordDensity = (getWordDensity(textValue));
const renderWordDensity = () => {
const wordDensityDiv = document.getElementById("word-density");
let table = "<table>";
for(let word in wordDensity){
table += "<tr><td>" + word + "</td><td>" + wordDensity[word] + "</td></tr>";
}
table += "</table>";
wordDensityDiv.innerHTML = "<h1> Word Density: </h1>" + table;
};
renderWordCount();
renderWordDensity();
};
<!DOCTYPE html>
<html>
<head>
<title>Word Counter</title>
</head>
<body>
<div id="input-page">
<h1>Word Counter</h1>
<form action="">
<textarea id="text" type="text" rows="22" cols="60"></textarea>
<br />
</form>
<button onclick="displayText()">COUNT</button>
</div>
<div id="count-page" style="display: none;">
<h1>Your Text:</h1>
<p id="display-text"></p>
<div id="word-count"></div>
<div id="word-density"></div>
</div>
</body>
<script src="app.js"></script>
</html>
添加回答
举报