这个Javascript代码如何更简洁地表达?

3

我有一些Python代码需要转换成Javascript:

word_groups = defaultdict(set)
for sentence in sentences:
    sentence.tokens = stemmed_words(sentence.str_)
    for token in sentence.tokens:
        word_groups[sentence.actual_val].add(token)

我对Javascript不是很了解,所以这是我能做到的最好:

var word_groups = {}
for(var isent = 0; isent < sentences.length; isent++) {
    var sentence = sentences[isent]
    sentence.tokens = stemmed_words(sentence.str_)
    for(var itoken = 0; itoken < sentence.tokens.length; itoken++) {
        var token = sentence.tokens[itoken]
        if(!(sentence.actual_val in word_groups))
            word_groups[sentence.actual_val] = []
        var group = word_groups[sentence.actual_val]
        if(!(token in group))
            group.push(token)
    }
}

有人能提供一些方法,使javascript代码更像python吗?


2
可能应该发布在codereview.stackexchange上。 - Jordan Running
3
你能让英语看起来更像中文吗? - epascarello
2
@epascarello,虽然我理解你的问题,但询问如何更简洁地表达JS代码是一个好问题。 - zzzzBov
你期望别人比你更加熟悉Python和JavaScript(实际上是ECMAScript)。最好解释一下Python代码的具体作用,以便建议一个合适的JavaScript等效代码。你的ECMAScript代码似乎有点混乱,特别是最后的if..in块。 - RobG
@RobG 我不确定我是否能比那段JavaScript代码更好地表达它。DefaultDict意味着字典会自动分配默认值,如果您尝试访问不存在的键。Set有点像列表,只是每个元素都是唯一的。因此,如果该键不在字典中,则为该键创建一个空集,并将令牌添加到集合中(这意味着如果值的实例已经存在,则不添加令牌)。 - Jesse Aldridge
显示剩余2条评论
3个回答

1

很有可能我错误地解释了你的Python代码的作用,但是假设你想要单词计数,我会将它写成如下形式:

var word_groups = {}
sentences.forEach(function (sentence) {
  sentence.tokens = stemmed_words(sentence.str_)
  sentence.tokens.forEach(function (token) {
    var val = sentence.actual_val
    word_groups[val] = (word_groups[val] || 0) + 1
  })
})

上述代码在输入中出现“constructor”一词时将失败。可以通过以下方式解决JavaScript的这个问题:
var word_groups = {}
sentences.forEach(function (sentence) {
  sentence.tokens = stemmed_words(sentence.str_)
  sentence.tokens.forEach(function (token) {
    var val = sentence.actual_val
    if (!word_groups.hasOwnProperty(val)) word_groups[val] = 0
    word_groups[val] += 1
  })
})

每个句子都有一个值(1、2或3),我想将具有相同值的每个句子中的唯一单词分组。因此,如果值为3的句子集合是['foo bar','foo baz','bar baz ball'],那么word_groups [3] == ['foo','bar','baz','ball']。 - Jesse Aldridge
forEach看起来很不错。谢谢你。 - Jesse Aldridge

1

我假设您正在使用一个支持 forEach 的环境,那么 reduceObject.keys 也应该可用(例如 ECMAScript >= 1.8.5):

var word_groups = sentences.reduce(function (groups, sentence) {
  var val = sentence.actual_val
  var group = groups[val] = groups[val] || []
  stemmed_words(sentence.str_).forEach(function (t) {
    if (!(t in group)) group.push(t)
  })
  return groups
}, {})

0
如果你的JavaScript版本不确定是否在1.6或更高版本(需要注意的是,IE 8的JavaScript版本为1.5),你可能需要使用jQuery作为兼容层。例如,$.each(a, f)与a.forEach(f)兼容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接