没有人知道一种简单的方法来计算Javascript字符串中一个单词的出现次数,而没有一个可用的预定义单词列表?理想情况下,我希望它输出到关联数组(Word,Count)。
例如,如果输入类似“你好,你好,你好”的内容,则会输出以下内容:-“你好”:2“如何”:1“是”:1“您”:1
非常感谢您的帮助。
谢谢,
var counts = myString.replace/[^\w\s]/g, "").split(/\s+/).reduce(function(map, word){
map[word] = (map[word]||0)+1;
return map;
}, Object.create(null));
对于一个简单的字符串,就足够了:
var str = "hello hello hello this is a list of different words that it is",
split = str.split(" "),
obj = {};
for (var x = 0; x < split.length; x++) {
if (obj[split[x]] === undefined) {
obj[split[x]] = 1;
} else {
obj[split[x]]++;
}
}
console.log(obj)
但是,如果您想处理句子,则需要对标点符号等进行一些处理(因此,将所有!!。替换为空格)