|
15 | 15 |
|
16 | 16 | import re |
17 | 17 | from collections import defaultdict |
18 | | -from typing import Iterator, List |
| 18 | +from typing import Iterator, List, Optional |
19 | 19 |
|
20 | | -from pythainlp.tokenize import DEFAULT_WORD_DICT_TRIE |
| 20 | +from pythainlp.tokenize import word_dict_trie |
21 | 21 | from pythainlp.util import Trie |
22 | 22 |
|
23 | 23 |
|
@@ -48,12 +48,11 @@ def __init__(self, value, multi=None, in_dict=True): |
48 | 48 |
|
49 | 49 |
|
50 | 50 | def _multicut( |
51 | | - text: str, custom_dict: Trie = DEFAULT_WORD_DICT_TRIE |
| 51 | + text: str, custom_dict: Optional[Trie] = None |
52 | 52 | ) -> Iterator[LatticeString]: |
53 | 53 | """Return LatticeString""" |
54 | 54 | if not custom_dict: |
55 | | - custom_dict = DEFAULT_WORD_DICT_TRIE |
56 | | - |
| 55 | + custom_dict = word_dict_trie() |
57 | 56 | len_text = len(text) |
58 | 57 | words_at = defaultdict(list) # main data structure |
59 | 58 |
|
@@ -123,40 +122,46 @@ def _combine(ww: List[LatticeString]) -> Iterator[str]: |
123 | 122 |
|
124 | 123 |
|
125 | 124 | def segment( |
126 | | - text: str, custom_dict: Trie = DEFAULT_WORD_DICT_TRIE |
| 125 | + text: str, custom_dict: Optional[Trie] = None |
127 | 126 | ) -> List[str]: |
128 | 127 | """Dictionary-based maximum matching word segmentation. |
129 | 128 |
|
130 | 129 | :param text: text to be tokenized |
131 | 130 | :type text: str |
132 | 131 | :param custom_dict: tokenization dictionary,\ |
133 | | - defaults to DEFAULT_WORD_DICT_TRIE |
| 132 | + defaults to a Trie generated from pythainlp.corpus.thai_words |
134 | 133 | :type custom_dict: Trie, optional |
135 | 134 | :return: list of segmented tokens |
136 | 135 | :rtype: List[str] |
137 | 136 | """ |
138 | 137 | if not text or not isinstance(text, str): |
139 | 138 | return [] |
140 | 139 |
|
| 140 | + if not custom_dict: |
| 141 | + custom_dict = word_dict_trie() |
| 142 | + |
141 | 143 | return list(_multicut(text, custom_dict=custom_dict)) |
142 | 144 |
|
143 | 145 |
|
144 | 146 | def find_all_segment( |
145 | | - text: str, custom_dict: Trie = DEFAULT_WORD_DICT_TRIE |
| 147 | + text: str, custom_dict: Optional[Trie] = None |
146 | 148 | ) -> List[str]: |
147 | 149 | """Get all possible segment variations. |
148 | 150 |
|
149 | 151 | :param text: input string to be tokenized |
150 | 152 | :type text: str |
151 | 153 | :param custom_dict: tokenization dictionary,\ |
152 | | - defaults to DEFAULT_WORD_DICT_TRIE |
| 154 | + defaults to word_dict_trie() |
153 | 155 | :type custom_dict: Trie, optional |
154 | 156 | :return: list of segment variations |
155 | 157 | :rtype: List[str] |
156 | 158 | """ |
157 | 159 | if not text or not isinstance(text, str): |
158 | 160 | return [] |
159 | 161 |
|
| 162 | + if not custom_dict: |
| 163 | + custom_dict = word_dict_trie() |
| 164 | + |
160 | 165 | ww = list(_multicut(text, custom_dict=custom_dict)) |
161 | 166 |
|
162 | 167 | return list(_combine(ww)) |
0 commit comments