Exemplo n.º 1
0
def trie_based_search():
    # trie-based search
    t = Trie()

    # load words in text into Trie
    with open(text_path, "r", newline="\n") as fin:
        print("Trie-based search for %s" % text_path)
        line: str
        text = fin.readlines()

        start_trie_load = time()
        # timing for loading words to Trie
        for i, line in enumerate(text):
            # replace all non-alphanumeric characters in string with empty str
            # generate list of words in line by splitting by space
            words = (re.sub(r"[^a-zA-Z0-9_ ]+", "", line)).split(' ')

            # iterate through each word in list and add to trie
            for word in words:
                t.add_word(word.lower())
        end_trie_load = time()

        print("Trie loading time: %s\n\n" % (end_trie_load - start_trie_load))

        print("Finished loading %s\n" % text_path)

    t.save_trie_to_disk()

    print("Number of unique beginning chars: %s" % len(t.children))
    word = input("Enter a word to search in %s: " % text_path)
    search_start = time()
    word_found = t.search_word(word=word)
    search_end = time()
    print("\twas %s found? %s\n" % (word, word_found))
    print("\ttime for search: %d" % (search_end - search_start))
Exemplo n.º 2
0
    def test_trie(self):
        words_dictionary = Trie()
        words = ["zoro", "luffy", "sanji", "nami", "brook", "jimbei", \
                "luf", "bro", "jim", "san"]
        for word in words:
            words_dictionary.insert_word(word)

        for word in words:
            self.assertTrue(words_dictionary.search_word(word))

        self.assertFalse(words_dictionary.search_word("sa"))
        self.assertFalse(words_dictionary.search_word("zor"))
        self.assertFalse(words_dictionary.search_word("sand"))
        self.assertFalse(words_dictionary.search_word("jimb"))
        self.assertFalse(words_dictionary.search_word("name"))
        self.assertFalse(words_dictionary.search_word("game"))