LineTokenizer.span_tokenize() doesn't split in `keep` mode (passes literal `\n`, not a newline)
Hey, I used Claude Code to dig through the tokenizers and it turned up a bug in LineTokenizer
when blanklines="keep".
tokenize() works fine, it keeps blank lines just like the class's own doctest says:
from nltk.tokenize.simple import LineTokenizer
s = "Good muffins cost $3.88\nin New York. Please buy me\ntwo of them.\n\nThanks."
lt = LineTokenizer(blanklines="keep")
lt.tokenize(s)
# ['Good muffins cost $3.88', 'in New York. Please buy me', 'two of them.', '', 'Thanks.']But span_tokenize() on that same string just hands back one span for the whole thing:
list(lt.span_tokenize(s))
# [(0, 73)]Traced it to nltk/tokenize/simple.py:127:
yield from string_span_tokenize(s, r"\n")r"\n" there is a raw string, so it's two characters, backslash and n, not an actual newline.
string_span_tokenize matches on that literal separator, so it's searching the text for
something that basically never shows up, and just falls back to one span covering everything.
span_tokenize's own docstring in nltk/tokenize/api.py:39-40 says the spans should be such
that s[start_i:end_i] is the corresponding token, so this breaks that contract for keep mode.
Fix looks like dropping the raw prefix:
yield from string_span_tokenize(s, "\n")Checked that this one-line change reconstructs tokenize()'s output exactly on the example above
before writing this up (per your #3883 note, flagging again that Claude Code did the repro and the
trace, not me by hand).
Happy to send a PR if this is the intended fix.
Source: nltk/nltk