matx.runtime.trie module

class matx.runtime.trie.Trie(dic=None)[source]

Bases: Object

Double Array Trie Object

Parameters:

dic (Dict[str, int]) – The key is word and the value is id

Examples

>>> import matx
>>> tree = matx.Trie({"hello": 1, "hello w": 2, "good": 3})
>>> tree
Trie(addr: 0x5601feb2aca0)
>>> tree = matx.Trie()
>>> tree
Trie(addr: 0x5601feba5b90)
__init__(dic=None)[source]
load(file_path: str)[source]

Find the longest substring of w[pos:] in the trie tree

Parameters:
  • w (str) – The input word

  • pos (int, optional) – The start position

Returns:

Return the length and id of the matched substring.

If not found, return (0, -1)

Return type:

Tuple(int, int)

Examples

>>> import matx
>>> tree = matx.Trie({"hello": 1, "hello w": 2, "good": 3})
>>> tree.prefix_search("hello world")
(7, 2)
>>> tree.prefix_search("hellf")
(0, -1)
prefix_search_all(w, pos=0)[source]

Find all substring of w[pos:] in the trie tree

Parameters:
  • w (str) – The input word

  • pos (int, optional) – The start position

Returns:

Return a list of the length and id of the matched substring.

If not found, return []

Return type:

List[Tuple(int, int)]

Examples

>>> import matx
>>> trie = matx.Trie({'hello': 1, 'hello world': 2, 'hello hello world': 3})
>>> trie.prefix_search_all("hello hello world")
[(5, 1), (17, 3)]
save(file_path: str)[source]
update(w, index=-1)[source]

Insert a word and corresponding id into the trie tree

Parameters:
  • w (str) – The input word

  • index (int, optional) – id, -1 for default

Examples

>>> import matx
>>> tree = matx.Trie()
>>> tree.update("hello", 1)
>>> tree.update("hello w", 2)
>>> tree.update("good", 3)
>>> tree.prefix_search("hello world")
(7, 2)
>>> tree.prefix_search("hellf")
(0, -1)
>>> tree.update("hell", 10)
>>> tree.prefix_search("hellf")
(4, 10)