Join word tokens back into readable text
Why it matters Chat UIs and evaluation scripts both need text that looks like the original, not a space-separated token dump.
A word-level tokenizer splits punctuation into its own tokens. Turning ids back into text needs spacing rules, or the output reads "Hello , world !".
Write detokenize(tokens). Join the tokens with single spaces, except: no space before a token in {".", ",", "!", "?", ";", ":", ")", "'s", "n't"}, and no space after the token "(". Return the string. An empty list gives "".
def detokenize(tokens)Example
detokenize(["Hello", ",", "world", "!"]) is "Hello, world!".
Understand the idea
Splitting text into words and punctuation is easy. Putting it back so it looks normal needs a few rules about spaces, like a typist who knows a comma sticks to the word before it.
Tokens: Hello , world ! . Start with "Hello". The comma attaches to the left, so no space: "Hello,". "world" is a normal word: add a space, "Hello, world". "!" attaches left: "Hello, world!".
Rule: for each token t, add a space first unless (a) the output is empty, (b) t is closing punctuation or a clitic like 's or n't, or (c) the previous token was "(". Then append t.
Subword tokenizers avoid this problem by storing the space inside the token, but word-level tokenizers in classic NLP pipelines, and the readable logs of many evaluation tools, still need a detokenizer like this one.