【问题标题】:Counting occurrences of a word in a string Javascript [closed]计算字符串Javascript中单词的出现次数[关闭]
【发布时间】:2013-02-01 13:40:42
【问题描述】:

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

例如,“Hello how are you Hello”这样的输入会输出如下内容:- “你好”:2 “如何”:1 “是”:1 “你”:1

非常感谢任何帮助。

谢谢,

【问题讨论】:

  • 你试过什么?出了什么问题?
  • 这里不是完成作业的地方。参考教程并学习 JavaScript。如果您卡在代码中,请在此处询问

标签: javascript string compare associative


【解决方案1】:

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

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)

如果您想处理句子,则需要对标点符号等进行一些处理(因此,将所有 !?. 替换为空格)

【讨论】:

  • 谢谢,太好了。正如其他人所说,这不是为了家庭作业,而是我正在做的一个项目。再次感谢。
  • 你不应该检查未定义的值,而是测试split[x] in obj
【解决方案2】:
var counts = myString.replace/[^\w\s]/g, "").split(/\s+/).reduce(function(map, word){
    map[word] = (map[word]||0)+1;
    return map;
}, Object.create(null));

【讨论】:

    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 2015-09-14
    • 2023-01-28
    • 1970-01-01
    • 2014-01-02
    • 2021-01-09
    相关资源
    最近更新 更多