Skip to content

Commit 2710adc

Browse files
authored
Merge pull request #1374 from phoneee/fix/word-detokenize-empty-string
fix: handle empty strings and empty list in word_detokenize
2 parents 9bc9bb5 + aed9d75 commit 2710adc

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

pythainlp/tokenize/core.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ def word_detokenize(
5252
"""
5353
list_all: list[list[str]] = []
5454

55+
if not segments:
56+
return "" if output == "str" else []
57+
5558
if isinstance(segments[0], str):
5659
segments = [segments] # type: ignore[assignment]
5760

@@ -63,6 +66,8 @@ def word_detokenize(
6366
space_index: list[int] = []
6467
mark_index: list[int] = []
6568
for j, w in enumerate(s):
69+
if not w:
70+
continue
6671
if j > 0:
6772
# previous word
6873
p_w = s[j - 1]
@@ -75,7 +80,7 @@ def word_detokenize(
7580
list_sents.append(" ")
7681
add_index.append(j)
7782
# if previous word is number or other language and is not space
78-
elif p_w[0] not in thai_characters and not p_w.isspace():
83+
elif p_w and p_w[0] not in thai_characters and not p_w.isspace():
7984
list_sents.append(" ")
8085
add_index.append(j)
8186
# if word is Thai iteration mark

tests/core/test_tokenize.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,12 @@ def test_word_detokenize(self):
233233
word_detokenize(["ม่ายย", " ", "ผม", "เลี้ยง", "5", "ตัว"]),
234234
"ม่ายย ผมเลี้ยง 5 ตัว",
235235
)
236+
# Reproduce: empty strings in token list should not cause IndexError
237+
self.assertIsInstance(word_detokenize(["สวัสดี", "", "ครับ"]), str)
238+
self.assertIsInstance(word_detokenize(["hello", "", "world"]), str)
239+
self.assertIsInstance(word_detokenize([""]), str)
240+
# Empty list should not crash
241+
self.assertEqual(word_detokenize([]), "")
236242

237243
def test_numeric_data_format(self):
238244
engines = ["newmm", "longest"]

0 commit comments

Comments
 (0)