句子特里/树/字典/语料库

时间:2018-05-18 17:09:31

标签: java dictionary tree text-mining trie

我希望建立一个树,其中节点是英文单词,叶子的分支形成一个句子。也就是说, a sentence tree (plz ignore the numbers):

我正在考虑使用Trie但是我在插入节点时遇到了麻烦。我不知道如何确定节点的级别。在Trie中,所有节点都是字符,因此可以使用它们。但言语不同。

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

谢谢!

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;
}

1 个答案:

答案 0 :(得分:0)

有点晚了,但也许即使现在我也能帮上忙。

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

尝试次数不止于此。如果我能正确理解您的意思,那么您希望按句子的组成词对句子进行排序。

在特里的每个级别,您都查看下一个单词并在子列表中查找其位置,而不是查看下一个字符。不幸的是,所有传统实现都显示了按字符排序。

我有一个解决方案,或者两个。第一种是使用my java source code trie。这将通过整数枚举对任何对象(在您的情况下,包含句子的字符串)进行排序。您将需要将单词映射为整数(将单词存储在trie中,每个单词都有一个唯一的数字),然后编写一个枚举器,返回一个单词的wordIntegers。那行得通。 (不要对单词使用哈希->整数转换,因为两个单词可以给出相同的哈希值。)

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

结果特里树将具有通用类型

Trie<K extends Comparable, T> 

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

Iterator<K extends Comparable> getIterator(T t)

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

使我的代码泛泛使用Comparable而不是Integer实际上非常容易。尽管有很多警告我使用的是原始类型的Comparable而不是Comparable。也许我会改天。

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下免费获得。