如何更简洁地表达此Javascript?

如何更简洁地表达此Javascript?,javascript,python,Javascript,Python,我有一些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了解不多,所以这是我能做的最

我有一些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)
    }
}
var word_groups={}
for(变量isent=0;isent<句子长度;isent++){
var句子=句子[isent]
句子.tokens=词干单词(句子.str)
for(var-itoken=0;itoken<句子.tokens.length;itoken++){
var token=句子.标记[itoken]
if(!(单词组中的句子.实际值))
单词组[句子.实际值]=[]
变量组=单词组[句子.实际值]
如果(!(组中的令牌))
组推送(令牌)
}
}

有人能提出一些方法让javascript代码看起来更像python吗?

我很可能误解了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
  })
})
如果输入中出现“构造函数”,上述操作将失败。可以解决这个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
  })
})

如果您不一定使用JavaScript1.6或更高版本(值得注意的是IE8使用JavaScript1.5),那么您可能希望jQuery作为一个兼容层。例如,$.each(a,f)与a.forEach(f)兼容。

我假设,如果您使用的环境中,
forEach
可用,
reduce
Object.key也可用。(例如ECMAScript>=1.8.5):


可能属于。你能让英语看起来更像中文吗?@epascarello,虽然我理解你问题的重点,但问如何以更简洁的方式表达JS代码是个好问题。你希望其他人比你更了解Python和javascript(ECMAScript)。最好确切地解释Python代码在做什么,这样就可以建议一个合适的javascript等价物。您的ECMAScript代码似乎有点混乱,尤其是最后一个if..in块。@RobG我真的不知道我是否能比Javascript代码更好地表达它。DefaultDict意味着如果您试图访问一个不存在的密钥,它会自动分配一个默认值的字典。集合有点像一个列表,只有每个元素是唯一的。因此,如果该键不在dict中,则为该键创建一个空集合,然后将令牌添加到集合中(这意味着如果该值的实例已经存在,则不添加令牌)。而不是在字数计算之后。每个句子都有一个值(1、2或3),我想将每个句子中具有相同值的唯一单词分组。所以基本上,如果一组值为3的句子是['foo-bar','foo-baz','bar-baz-ball'],那么单词组[3]==['foo','bar','baz','ball']forEach看起来确实不错。谢谢你。
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
}, {})