Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass Loose reference https://en.wikipedia.org/wiki/Trie
| 51 | |
| 52 | |
| 53 | class Trie: |
| 54 | """ |
| 55 | Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass |
| 56 | Loose reference https://en.wikipedia.org/wiki/Trie |
| 57 | """ |
| 58 | |
| 59 | def __init__(self, *args): |
| 60 | self.data = {} |
| 61 | self._tokens = set() |
| 62 | self._termination_char = "" |
| 63 | self.update(*args) |
| 64 | |
| 65 | def update(self, *args): |
| 66 | """ |
| 67 | Updates the Trie with new tokens provided as arguments. |
| 68 | |
| 69 | Args: |
| 70 | *args: Variable number of words to be added to the Trie. |
| 71 | """ |
| 72 | for token in tuple(*args): |
| 73 | self.add(token) |
| 74 | |
| 75 | def add(self, word: str): |
| 76 | """ |
| 77 | Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation. |
| 78 | The special key `""` in `self._termination_char` is used to represent termination. |
| 79 | |
| 80 | This function is idempotent, adding twice the same word will leave the trie unchanged |
| 81 | |
| 82 | Example: |
| 83 | |
| 84 | ```python |
| 85 | >>> trie = Trie() |
| 86 | >>> trie.add("Hello 友達") |
| 87 | >>> trie.data |
| 88 | {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} |
| 89 | |
| 90 | >>> trie.add("Hello") |
| 91 | >>> trie.data |
| 92 | {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} |
| 93 | ``` |
| 94 | """ |
| 95 | if not word: |
| 96 | # Prevent empty string |
| 97 | return |
| 98 | |
| 99 | self._tokens.add(word) |
| 100 | ref = self.data |
| 101 | for char in word: |
| 102 | ref[char] = ref.setdefault(char, {}) |
| 103 | ref = ref[char] |
| 104 | ref[self._termination_char] = 1 |
| 105 | |
| 106 | def split(self, text: str) -> List[str]: |
| 107 | """ |
| 108 | Will look for the words added to the trie within `text`. Output is the original string splitted along the |
| 109 | boundaries of the words found. |
| 110 |
no outgoing calls