Skip to content

Commit 831a9fc

Browse files
authored
Merge pull request #382 from PyThaiNLP/refactor-trie
Refactor Trie __init__, reduce complexity
2 parents eda6f77 + 3faa0cc commit 831a9fc

2 files changed

Lines changed: 34 additions & 12 deletions

File tree

pythainlp/util/trie.py

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,38 @@ class Node(object):
1414
def __init__(self):
1515
self.end = False
1616
self.children = {}
17-
18-
def add(self, ch: str):
19-
child = self.children.get(ch)
20-
if not child:
21-
child = Trie.Node()
22-
self.children[ch] = child
23-
return child
2417

2518
def __init__(self, words: Iterable[str]):
26-
self.words = words
19+
self.words = set(words)
2720
self.root = Trie.Node()
2821

2922
for word in words:
30-
cur = self.root
31-
for ch in word:
32-
cur = cur.add(ch)
33-
cur.end = True
23+
self.add(word)
24+
25+
def add(self, word: str) -> None:
26+
"""
27+
Add a word to the trie.
28+
29+
:param str text: a word
30+
"""
31+
self.words.add(word)
32+
cur = self.root
33+
for ch in word:
34+
child = cur.children.get(ch)
35+
if not child:
36+
child = Trie.Node()
37+
cur.children[ch] = child
38+
cur = child
39+
cur.end = True
3440

3541
def prefixes(self, text: str) -> List[str]:
42+
"""
43+
List all possible words from first sequence of characters in a word.
44+
45+
:param str text: a word
46+
:return: a list of possible words
47+
:rtype: List[str]
48+
"""
3649
res = []
3750
cur = self.root
3851
for i, ch in enumerate(text):
@@ -50,6 +63,9 @@ def __contains__(self, key: str) -> bool:
5063
def __iter__(self) -> Iterable[str]:
5164
yield from self.words
5265

66+
def __len__(self) -> int:
67+
return len(self.words)
68+
5369

5470
def dict_trie(dict_source: Union[str, Iterable[str], Trie]) -> Trie:
5571
"""

tests/test_util.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,12 @@ def test_trie(self):
249249
self.assertIsNotNone(Trie(("ทอด", "ทอง", "ทาง")))
250250
self.assertIsNotNone(Trie(Trie(["ทดสอบ", "ทดลอง"])))
251251

252+
trie = Trie(["ทด", "ทดสอบ", "ทดลอง"])
253+
self.assertTrue("ทด" in trie)
254+
trie.add("ทบ")
255+
self.assertEqual(len(trie), 4)
256+
self.assertEqual(len(trie.prefixes("ทดสอบ")), 2)
257+
252258
self.assertIsNotNone(dict_trie(Trie(["ลอง", "ลาก"])))
253259
self.assertIsNotNone(dict_trie(("ลอง", "สร้าง", "Trie", "ลน")))
254260
self.assertIsNotNone(dict_trie(["ลอง", "สร้าง", "Trie", "ลน"]))

0 commit comments

Comments
 (0)