Define and Implement a Streaming Unicode Word Counter
StringsModel answerLast updated
Specify precise tokenization rules for counting words in text, then build a Unicode-aware counter that works on huge streams, with tests and a regex versus scanner comparison.
You are asked to write a function that reports how many words a text document contains. "Word" is ambiguous, so part of the task is to pin the definition down yourself.
What to do
- Write down your tokenization rules before coding. Cover at least:
- Contractions such as
it'sandit’s. - Hyphenated compounds such as
state-of-the-art. - Numbers with separators such as
3.14and1,000. - Surrounding punctuation, quotes and Unicode apostrophes.
- Runs of whitespace, tabs and newlines.
- Text in several scripts, including languages written without spaces.
- Contractions such as
- Implement
count_wordsfollowing those rules. - Support very large inputs. The same logic must work on a multi-gigabyte file or a network stream read in chunks, and a word that straddles two chunks must be counted once.
- Write unit tests for corner cases: empty input, whitespace only, punctuation only, mixed languages, combining accents, and chunk boundaries.
- Analyze time and space complexity.
- Compare a regex-based tokenizer with a hand-written character scanner, and say when you would choose each.
Expected output: the list of rules, working code, tests, the complexity analysis and a short trade-off discussion. Defend your choices, since the rules matter as much as the code.
Hints
Hint 1
Decide what counts as a word character first. Unicode general categories (letters, numbers, combining marks) are a better basis than ASCII ranges, and they handle accented and non-Latin text.
Hint 2
Treat apostrophes, hyphens and, between digits only, periods and commas as connectors. A connector joins two word characters only if a word character is on both sides. Hold it as pending until the next character arrives.
Hint 3
Model the counter as a small state machine (in a word or not, pending connector, last character was a digit) and increment the count exactly when a new word begins. Because the state is tiny, you can feed it chunks of any size, and a word split across chunks is still counted once.
Hint 4
For the regex comparison, think about what happens when a match straddles a chunk boundary, and how you would handle that with a regex versus with scanner state.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Most of the work is the definition. Fix the rules, then implement them as a one-pass state machine. All state sits in a few variables, so the same scanner works on a string, a huge file, or a stream.
Tokenization rules
- Word characters are Unicode letters, digits and combining marks (categories
L*,N*,M*). This handlescafé,мир, Arabic-Indic digits, and decomposed accents likee+ U+0301. - Internal connectors join two word characters into one word only when a word character is on both sides:
- Apostrophes
',’,ʼ,':it'sandit’sare one word. - Hyphens
-, U+2010, U+2011:state-of-the-artis one word. .and,only between digits:3.14and1,000are one word, butend.Startis two.
- Apostrophes
- A doubled connector breaks the word, so
well--knownis two words. Em and en dashes always separate. - Leading and trailing quotes or apostrophes are punctuation, so
'quoted'is the wordquoted. - Everything else separates words: punctuation, any run of whitespace, emoji and symbols. Several spaces behave like one.
- CJK (Han, Hiragana, Katakana) has no spaces, so each character counts as one word. Hangul uses spaces and is treated as ordinary letters.
- Soft hyphen (U+00AD) and zero-width joiner are ignored and never split a word.
- Documented simplifications:
e.g.counts as two words, and Thai or Lao would need dictionary segmentation (for example ICU).
State these up front. An interviewer mostly wants to see that you noticed the ambiguity and chose consistently.
Why the scanner is correct
The count goes up exactly when a new word starts, which happens in two cases:
- A word character arrives while we are outside a word.
- A word character arrives after a pending connector that is not valid there, such as
.between letters.
A connector is never committed immediately. It is held as pending until the next character decides whether the word continues. A trailing it' or a chunk ending in state- is therefore resolved when the next character arrives, even in the next chunk. If you read in text mode, Python's incremental decoder keeps UTF-8 sequences split across reads intact, so the scanner only sees whole code points.
Code
import unicodedata
from functools import lru_cache
from typing import Iterable
APOSTROPHES = {"'", "\u2019", "\u02BC", "\uFF07"}
HYPHENS = {"-", "\u2010", "\u2011"}
NUMERIC_SEPS = {".", ","}
CONNECTORS = APOSTROPHES | HYPHENS | NUMERIC_SEPS
IGNORABLE = {"\u00AD", "\u200D"}
@lru_cache(maxsize=65536)
def _is_word_char(ch):
return unicodedata.category(ch)[0] in "LNM"
def _is_cjk(ch):
cp = ord(ch)
return (0x4E00 <= cp <= 0x9FFF or 0x3400 <= cp <= 0x4DBF
or 0x20000 <= cp <= 0x2A6DF or 0xF900 <= cp <= 0xFAFF
or 0x3040 <= cp <= 0x30FF)
class WordCounter:
def __init__(self):
self.count = 0
self._in_word = False
self._pending = None
self._last_digit = False
def feed(self, text):
for ch in text:
if ch in IGNORABLE:
continue
if _is_cjk(ch):
self.count += 1
self._in_word, self._pending = False, None
elif _is_word_char(ch):
if self._in_word and self._pending is not None:
if self._pending in NUMERIC_SEPS and not (
self._last_digit and ch.isdigit()):
self.count += 1 # "end.Start"
elif not self._in_word:
self.count += 1
self._in_word, self._pending = True, None
self._last_digit = ch.isdigit()
elif ch in CONNECTORS and self._in_word and self._pending is None:
self._pending = ch
else:
self._in_word, self._pending = False, None
def count_words(text):
wc = WordCounter()
wc.feed(text)
return wc.count
def count_words_stream(chunks: Iterable[str]):
wc = WordCounter()
for c in chunks:
wc.feed(c)
return wc.count
def count_words_file(path, encoding="utf-8", chunk_size=1 << 20):
with open(path, encoding=encoding, errors="replace") as f:
return count_words_stream(iter(lambda: f.read(chunk_size), ""))
Tests worth writing
""and" \n\t "give 0.- Punctuation only (
"!!! ... --- ? '") gives 0. "It's state-of-the-art."gives 2, and"well--known"gives 2."Pi is 3.14, not 3,14159."gives 5, and"end.Start"gives 2."'quoted' and “double”"gives 3.- Decomposed accents:
"cafe\u0301 nai\u0308ve"gives 2. - Mixed scripts:
"Hello 世界 мир"gives 4,"日本語"gives 3,"안녕 세상"gives 2. - Chunk boundaries:
["sta", "te-of-", "the-art and it", "'s"]gives 3. Also compare the result for every possible split point of a sample string against the unsplit result. - A large stream such as 100,000 repetitions of
"word ".
Complexity
- Time: O(n) in characters, with O(1) work per character. Category lookups are cached.
- Space: O(1) scanner state plus O(chunk size) for the buffer, so memory is the same for 1 KB or 100 GB.
For very large files the Python loop is the bottleneck, at roughly a few million characters per second. Options are to process shards of the file in parallel (cut at whitespace so no word is split, and sum the counts), or to skip the per-character work for ASCII-only chunks with a fast path.
Regex versus manual scanner
Regex (the third-party regex module, for \p{..} classes):
[\p{L}\p{N}\p{M}]+(?:['’ʼ\-‐‑][\p{L}\p{N}\p{M}]+|(?<=\p{N})[.,]\p{N}+)*
- Pros: concise, declarative, runs in C, often 5-20x faster than a Python loop, easy to review.
- Cons: streaming is awkward because a match can straddle a chunk boundary. You must hold back the trailing partial token and prepend it to the next chunk, which is where bugs hide. The CJK per-character rule and ignorable characters add complexity. Pathological backtracking is possible with sloppy patterns, and the standard
remodule lacks Unicode property classes.
Manual scanner:
- Pros: truly O(1) state and trivial streaming, with exact control over edge cases. Easy to extend and to port to another language.
- Cons: more code, slower in pure Python, and more room for off-by-one mistakes.
Recommendation: use the regex for in-memory text where speed and brevity matter. Use the scanner when streaming correctness is the priority, or write it in a compiled language when throughput matters.
Common mistakes
- Using
str.split()and calling it done. Punctuation stays attached, and CJK text is undercounted. - Using
[A-Za-z]and breaking on accents or non-Latin scripts. - Counting
'or-as part of a word wherever they appear, so that'quoted'or a lone-becomes a word. - Splitting
3.14into two words. - Reading the whole file into memory, or losing a word at a chunk boundary.
- Not stating the rules, so the answer cannot be judged as right or wrong.