句子Trie/树/字典/语料库



我希望建立一棵树,其中节点是英语单词,树叶的分支形成一个句子。即 句子树(请忽略数字):

我想使用 Trie,但在插入节点时遇到问题。我不确定如何确定节点的级别。在 Trie 中,所有节点都是字符,因此可以使用 .但有话就不一样了。

有意义吗?我也对其他数据结构持开放态度。目标是创建一个存储一堆英语句子的词典/语料库。用户可以使用前几个单词来查找整个句子。我最精通Java,但我也知道python,如果它们更容易用于我的目的,我就是这样。

谢谢!

void insert(String key) {
int level;
int length = key.length();
int index;
TrieNode pCrawl = root;
for (level = 0; level < length; level++)
{
index = key.charAt(level) - 'a';
if (pCrawl.children[index] == null)
pCrawl.children[index] = new TrieNode();
pCrawl = pCrawl.children[index];
}
// mark last node as leaf
pCrawl.isEndOfWord = true;
}

有点晚了,但也许我现在也可以帮上一点忙。

trie 按唯一键对每个级别进行排序。 传统上,这是字符串中的字符,存储在最终位置的值是字符串本身。

尝试可能远不止于此。 如果我理解正确,那么你希望按组成词对句子进行排序。

在你尝试的每个级别,你都会看下一个单词,并寻找它在子项列表中的位置,而不是看下一个角色。 不幸的是,所有传统实现都显示按字符排序。

我有一个解决方案给你,或者更确切地说是两个。首先是使用我的java源代码trie。 这将通过整数枚举对任何对象(在您的情况下是包含句子的字符串)进行排序。您需要将单词映射到整数(将单词存储在trie中,为每个单词提供一个唯一的数字),然后编写一个枚举器,为句子返回wordIntegers。 那会起作用。 (不要对单词 -> 整数转换使用哈希,因为两个单词可以给出相同的哈希)。

第二种解决方案是采用我的代码,而不是比较整数,而是将单词作为字符串进行比较。 这将需要更多的工作,但看起来完全可行。 事实上,我怀疑我的解决方案可以通过将整数枚举替换为可比枚举来使我的解决方案更加通用。 如果你想这样做,或者合作做这件事,我会很感兴趣。 哎呀,我什至可能为了好玩而自己做。

生成的 trie 将具有泛型类型

Trie<K extends Comparable, T> 

并将针对 K 序列存储 T 的实例。 编码人员需要定义一个方法

Iterator<K extends Comparable> getIterator(T t)

================================编辑: ====

=======================实际上,将我的代码概括为使用可比较而不是整数非常容易。 尽管有很多警告说我使用的是原始类型的可比而不是可比。 也许我改天会解决这些问题。

SentenceSorter sorter = new SentenceSorter();
sorter.add("This is a sentence.");
sorter.add("This is another sentence.");
sorter.add("A sentence that should come first.");
sorter.add("Ze last sentence");
sorter.add("This is a sentence that comes somewhere in the middle.");
sorter.add("This is another sentence entirely.");

然后按以下方式列出句子:

Iterator<String> it = sorter.iterator();
while (it.hasNext()) {
System.out.println(it.next()); 
}

A sentence that should come first.
This is a sentence that comes somewhere in the middle.
This is a sentence.
This is another sentence entirely.
This is another sentence.

请注意,句子拆分包括带有 ord 的句号,这会影响排序。 你可以对此进行改进。

我们可以证明我们按单词而不是字符排序:

it = sorter.sentencesWithPrefix("This is a").iterator();
while (it.hasNext()) {
System.out.println(it.next()); 
}

This is a sentence that comes somewhere in the middle.
This is a sentence.

it = sorter.sentencesWithPrefix("This is another").iterator();
while (it.hasNext()) {
System.out.println(it.next()); 
}

This is another sentence entirely.
This is another sentence.

希望有帮助 - 代码都在上面提到的存储库中,并在 Apache2 下免费提供。

最新更新