所以,我试着做一个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实现一样工作?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐