[英]How do I count the number of times each word appears in a string?
I'm learning JavaScript now and I'm working on a function that will count how many times words show up in a string, then spits out the answer as an object. 我现在正在学习JavaScript,并且正在开发一个函数,该函数将计算单词在字符串中出现的次数,然后将答案作为对象吐出来。 Per some suggestions on similar threads on this site, I've decided to use .split and a counter function to make a two-dimensional array, then populate an object with the results.
根据该站点上类似线程的一些建议,我决定使用.split和一个计数器函数来制作二维数组,然后使用结果填充对象。 I was running tests with sample texts, when I ran into some trouble with certain strings.
当我遇到某些字符串问题时,我正在用示例文本运行测试。 I can't figure out why some of the counters are showing up as undefined.
我不知道为什么某些计数器显示为未定义。
function countWords(str) {
var answer = {};
if (str === '') {
return answer;
}
var strArray = [];
strArray = str.split(' ');
//strArray is an array that holds the words as separate strings
console.log('strArray: ' + strArray);
var resultWords = [];
var resultCount = [];
var counter = 0;
// only if the word doesnt show up in resultWords, push it in, and increase the counter. if it has shown up, disregard
for (var i = 0; i<strArray.length; i++) {
counter = 0;
if (resultWords.indexOf( strArray[i] ) === -1) {
resultWords.push(strArray[i]);
counter += 1;
// if the word shows up again, increase the counter
for (var j = i + 1; j < strArray.length; j++) {
if (resultWords[i] === strArray[j]) {
counter += 1;
}
// push to resultCount the counter for each word
resultCount[i] = counter;
}
}
// create an object where the key is the word from resultWords and the value is the number from wordCount
for (var k = 0; k < resultWords.length; k++) {
answer[ resultWords[k] ] = resultCount[k];
}
}
console.log('resultWords: ' + resultWords);
console.log('resultCount: ' + resultCount);
return answer;
}
var sample = 'how now brown cow how now';
console.log(sample);
var output = countWords( sample );
I find that when I use the words "this" and "is" in my sample, I'm often returning "undefined" as the word count for those words. 我发现在示例中使用单词“ this”和“ is”时,我经常返回“ undefined”作为这些单词的单词计数。 For example, "to be or not to be" returns "undefined" for "that" and "is."
例如,“成为或不成为”将为“那个”和“是”返回“未定义”。 Can someone help elucidate what's going on here?
有人可以帮助阐明这里发生了什么吗? Thank you.
谢谢。
Your code is unreadable: 您的代码不可读:
answer
) answer
) Next, your algorithm is very slow: you can count words by parsing the whole array only once. 其次,您的算法非常慢:您可以通过仅解析整个数组一次来计数单词。
Last but not least, you should create the answer
array outside the loop. 最后但并非最不重要的一点是,您应该在循环外部创建
answer
数组。
Here's a shorter implementation that use modern javascript features (for the sake of learning): 这是使用现代javascript功能的较短实现(出于学习目的):
function countWords(str) {
const wordCounts = new Map()
str.split(' ').forEach(word => {
const currentWordCount = wordCounts.get(word) || 0
wordCounts.set(word, currentWordCount+1)
})
/* Reproduce your output */
const resultWords = [...wordCounts.keys()]
const resultCount = [...wordCounts.values()]
console.log('resultWords: ' + resultWords);
console.log('resultCount: ' + resultCount);
return wordCounts
}
On older js environment, you cannot use Map
and arrow functions: 在较旧的js环境中,不能使用
Map
和arrow函数:
function countWords(str) {
const wordCounts = {}
str.split(' ').forEach(function(word) {
const currentWordCount = wordCounts[word] || 0
wordCounts[word] = currentWordCount+1
})
/* Reproduce your output */
const resultWords = Object.keys(wordCounts)
const resultCount = resultWords.map(function(word) { return wordCounts[word] })
console.log('resultWords: ' + resultWords);
console.log('resultCount: ' + resultCount);
return wordCounts
}
Go back to your code, you get some undefined
because of this line: 回到您的代码,由于此行,您得到了一些
undefined
代码:
// push to resultCount the counter for each word
resultCount[i] = counter;
The index i
is the index of the current word in strArray
. 索引
i
是strArray
当前单词的strArray
。 You can fix it by removing this line, and do 您可以通过删除此行来修复它,然后执行
resultCount.push(counter)
After the end of the loop that starts with for (var j = i + 1; j < strArray.length; j++)
. 在以
for (var j = i + 1; j < strArray.length; j++)
开始的循环结束之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.