计算字符串Javascript中单词的出现次数

时间:2013-02-16 19:09:52

标签: javascript string compare associative

有没有人知道一种简单的方法来计算Javascript字符串中单词的出现次数,而没有预定义的单词列表可用?理想情况下,我希望它输出到一个关联数组(Word,Count)。

例如,沿“你好你好,你好怎么样”的输入会输出以下内容: - “你好”:2 “怎么样”:1 “是”:1 “你”:1

非常感谢任何帮助。

谢谢,

2 个答案:

答案 0 :(得分:3)

对于一个简单的字符串,这应该足够了:

str = "hello hello hello this is a list of different words that it is";

var 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]]++;
  }
}

如果你想处理句子,你需要处理标点符号等(所以,用空格替换所有!?。)

答案 1 :(得分:3)

var counts = myString.replace/[^\w\s]/g, "").split(/\s+/).reduce(function(map, word){
    map[word] = (map[word]||0)+1;
    return map;
}, Object.create(null));
相关问题