在Javascript中

时间:2015-12-10 04:43:18

标签: javascript python trie

所以,我试图制作一个将句子中的单词联系起来而不是单词前缀的trie。我已经设法在Python中完成了这项工作,如下所示:

#statement trie

class strie (object):

def __init__(self):
    self.trie = {}
def __repr__(self):
    return str(self.trie)
def __str__(self):
    return str(self.trie)
def statement(self, phrase):
    words = phrase.split()
    current = self.trie
    while len(words) > 0:
        word = words.pop(0)
        if word in current.keys():
            current = current[word]
        else:
            current[word] = {}
            current = current[word]

我会通过测试得到结果:

       r
=> {'The': {'apple': {'is': {'red': {}, 'blue': {'or': {'yellow': {}}}}}}}

但是,当我使用javascript几乎完全相同时,会发生一些奇怪的事情。这是我在javascript中的实现:

    //constructs a trie formed form a single sentence as an object.
function single_trie(phrase) {
    phrase = phrase.toLowerCase();
    var trie = {};
    var words = phrase.split(" ");
    var current = trie;
    while (words.length > 0) {
        var word = words.shift();
        if(word in current) current = current[word];
        else {
            current[word] = {};
            current = current[word];
        }
    }
    return trie;
}

我得到了这个非常奇怪的结果:

    var strie = single_trie("the apple is red and blue");
console.log(strie);

{ the: { apple: { is: [Object] } } }

我的javascript实现会导致这种情况发生的原因是什么?为什么显示[对象]?我怎样才能让它像我的python实现一样工作?

0 个答案:

没有答案