我正在尝试实现一个频率函数,它应该返回一个对象,其中包含单词列表中每个单词的属性。属性的值应该是单词在文本中出现的次数。我只能返回计数的数量,但我不知道如何返回一个对象。答案应该是{"bar":2、"foo":3}这样的对象。
function frequencies(str,wordlist){
var count = 0;
var count2 = 0;
var freqw = {};
var text1 = str.split(' ');
for(var i = 0; i < wordlist.length; i++){
if(str.match(wordlist[i]))
count++;
}
return count;
}
console.log(frequencies('foo foo bar foo bar buz', ['foo', 'bar']));发布于 2016-11-20 23:13:07
您需要使用indexOf代替匹配,还需要循环输入字符串,而不是字列表。
function frequencies(str,wordlist){
var count = 0;
var count2 = 0;
var freqw = {};
var text1 = str.split(' ');
for(var i = 0; i < wordlist.length; i++){
freqw[wordlist[i]] = 0;
}
for(var i = 0; i < text1.length; i++){
if(freqw[text1[i]] !== undefined) //check if word exists
freqw[[text1[i]]]++;
}
return freqw;
}
console.log(frequencies('foo foo bar foo bar buz', ['foo', 'bar']));发布于 2016-11-20 23:17:05
您可以减少单词列表,并通过对每个单词进行拆分来计数出现的次数。
function frequencies(str,wordlist){
return wordlist.reduce( (a,b) => {
return a[b] = str.split(new RegExp('\\b'+b+'\\b','g')).length-1,a;
},{})
}
console.log(frequencies('foo foo bar foo bar buz', ['foo', 'bar']));
发布于 2016-11-20 23:16:11
您可以为对象中的每个单词积累计数。
类似于:
function frequencies(str, wordlist) {
let words = str.split(' ');
let count = {};
words.forEach(function(word) {
if (wordList.indexOf(word) >= 0) {
if (!count[word]) count[word] = 0;
count[word] += 1;
}
});
return count;
}https://stackoverflow.com/questions/40710509
复制相似问题