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 "".

Signaturedef 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampledetokenize(['Hello', ',', 'world', '!'])
  • Sample 2: bracketsdetokenize(['call', '(', 'x', ')', 'now', '.'])
  • Test 3: contractionsdetokenize(['I', 'do', "n't", 'know', 'Sam', "'s", 'plan', '?'])
  • Test 4: emptydetokenize([])