Run over Reuters-21578 (10,788 stories, 1,549,426 NLTK tokens), the choices of HW01, a course indexer in Python, show what each pipeline decision costs. Reading with errors='ignore' deletes undecodable bytes without a trace, so a Latin-1 résumé is indexed as rsum. The isalpha() filter drops 7.7 percent of the tokens although they contain letters or digits, seven in ten of them numbers. Stemming query terms twice changes the stem of 1,060 of 27,959 distinct words (3.8 percent), and 792 of those queries then match nothing. A dictionary of Python sets takes 44.50 MB, about sixty times the 0.76 MB of variable-byte postings. The fixes: replacement decoding with error counts, sorted filenames, explicit token rules, one analyzer saved with the index, and sorted arrays with frequencies.
The first assignment in the course was to build an inverted index over a directory of text documents. It had to remove stop words, stem terms, report the most frequent terms and the index's memory use, and save the index for later use. My solution, HW01 in the information-retrieval repository, does all of that in about 600 lines of Python using NLTK, including a parser for Boolean queries. It works, and on the assignment's collection it produces sensible results. Every article of this topic so far has described one decision of an indexing pipeline. What do those decisions look like inside an ordinary indexer, where many of them are made in a few lines?
Reading HW01 again after writing the rest of this topic shows how many of them are made without being noticed as decisions at all. This article walks through the pipeline stage by stage. For each stage it describes what the code does, which concept from the topic it embodies, and what I would change. The aim is not to criticize a homework assignment, which met its requirements, but to show where the theory of this topic meets real code.
Here is the route. First come reading files and assigning document identifiers. Then the single line that tokenizes, filters, and stems, and what it does to Reuters-21578. Next the postings representation and what it costs in memory. Finally saving the index and building it in parallel, followed by a table of the changes.
To make the stages concrete, the measurements below run HW01's choices over a larger collection than the assignment's. That collection is Reuters-21578 (Lewis, 1997), the 10,788 news stories that the term statistics and index compression articles also use. The scripts apply the same NLTK tokenizer, filter, and stemmer (Bird, Klein, and Loper, 2009), without stop-word removal.
Reading files
The indexer lists the files in a directory, keeps those ending in .txt, and reads each one:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
text = f.read()
Specifying UTF-8 is right for most modern text. The errors='ignore' argument is the part to watch. It tells Python to drop any bytes that are not valid UTF-8, without reporting them. A file saved in Latin-1 containing résumé would be read as rsum, the silent deletion described in from bytes to documents. The program never fails, and the altered terms simply enter the index.
The bytes are easy to inspect. Latin-1 stores é as the single byte 0xE9, which can never stand alone in valid UTF-8. Decoding r\xe9sum\xe9 with errors='ignore' yields rsum.
Example (errors='replace'). Decoding the same bytes with errors='replace' yields r�sum�, which is more useful. The two replacement characters, U+FFFD, mark exactly where the damage is. The word is still damaged, but now the damage can be counted and reported.
What I would change: decode with errors='replace', count the replacement characters in each file, and report files with many of them. Those are almost certainly in another encoding and can be re-read with the right one. Choosing documents by extension suits a directory of .txt files. The course project's later requirement to handle several formats calls for a dispatcher that identifies each file's format and passes it to an appropriate text extractor.
Assigning document identifiers
Each file receives an integer docID in the order the directory listing returns it. Directory listing order is not guaranteed, and it differs between operating systems and file systems. So the same collection can produce different docIDs on different machines, and results then look different even when nothing else has changed.
The two build modes also apply different rules. The single-process build skips empty files. The parallel build, which divides the files among worker processes, does not check for empty files, so they receive docIDs there. The same directory can therefore produce different document counts depending on which mode runs. That in turn changes any statistic that depends on the number of documents, such as inverse document frequency.
What I would change: sort the filenames before assigning docIDs, and put the rules for skipping a file in one function that both build modes call.
Tokenizing and filtering
The core of the indexer is one list comprehension:
tokens = [self.stemmer.stem(word.lower())
for word in nltk.word_tokenize(text)
if word.isalpha() and word.lower() not in self.stopwords]
This line performs tokenization, case folding, stop-word removal, and stemming, in the order recommended in the stop words article.
The isalpha() filter has a larger effect than it appears to. It keeps only tokens made entirely of letters. The tokenization article opens with a sentence that NLTK's tokenizer splits into fifteen tokens:
O'Neill's state-of-the-art C++ library wasn't released until 3/20/91 (see www.example.com).
Example (what survives the filter). Five of the fifteen tokens survive isalpha(): library, was, released, until, and see. O'Neill, state-of-the-art, C++, the date, the web address and the split-off pieces 's and n't are all discarded, along with the three punctuation tokens the filter was meant to remove.
The filter on a whole collection
On Reuters-21578 the tokenizer produces 1,549,426 tokens.
- The filter keeps the 82.4 percent that are purely alphabetic.
- It removes the 9.9 percent that are pure punctuation, as intended.
- It also removes another 7.7 percent, 119,961 tokens, that contain letters or digits.
Seven in ten of those are numbers, which in a financial newswire carry much of the content: prices, quantities, and dates. The most common of the rest are the possessive 's, which NLTK splits off as a token of its own, and the abbreviation U.S., which occurs 4,919 times and is unsearchable after filtering. For the assignment's documents, the filter was a reasonable way to keep the vocabulary clean. For a general collection, it makes names with apostrophes, hyphenated terms, every number, and every technical identifier unsearchable.
What I would change: replace the filter with explicit rules. Drop pure punctuation, keep tokens that contain letters or digits, and decide deliberately what to do with apostrophes and hyphens, for example by indexing both the joined form and its parts. The query side must apply exactly the same rules, which leads to the next point.
Stemming consistently
The stemmer is NLTK's PorterStemmer() with no arguments. By default, that class applies NLTK's extensions to the original Porter algorithm. It gives different stems from the original for words such as dying, skies, news, and ice (see the Porter stemmer). That is fine, provided queries are stemmed in exactly the same way.
In HW01 the query parser takes the index's stop list, but it creates its own PorterStemmer() with the same default settings and repeats the tokenizing and filtering rules in its own code. Rereading it for this article showed a consequence of that duplication that is easy to miss: the parser stems each query term twice. It stems once when it tokenizes the query and again when it looks the term up.
Example (stemming a stem). The Porter stemmer turns university into univers, and a second pass does not leave univers alone. The stemmer is not idempotent: stemming a stem can shorten it further, and univers becomes univ. A query for university therefore looks up univ, which is not in the index, and silently matches nothing. Decisively goes from decis to deci in the same way. Most words survive a second stemming unchanged, which is why the effect went unnoticed in testing.
Reuters-21578 shows how often they do not. Of the collection's 27,959 distinct lowercase words, 1,060 (3.8 percent) have a stem that changes when stemmed again. These words account for 2.0 percent of all word occurrences. (The Porter stemmer article counts 1,134 of 28,390 words, 4.0 percent, for the same collection: it uses a regular-expression tokenizer and the original algorithm, where this count uses HW01's NLTK tokenizer, its letters-only filter and NLTK's default mode.) For 792 of them the doubly stemmed form is not a term in the index at all, so a query silently matches nothing. The other 268 behave differently, and less visibly, because the second stem is another word's stem. Examples of both kinds:
| Query word | Indexed as | Looked up as | Result |
|---|---|---|---|
| increase | increas |
increa |
matches only the misspellings increaes and increas |
| because | becaus |
becau |
no match |
| house | hous |
hou |
no match |
| financial | financi |
financ |
matches finance |
| japanese | japanes |
japan |
matches Japan |
Increase is the most frequent affected word in the collection, and a query for it finds only the few stories in which the wire misspelled it. Querying japanese returns the stories that mention Japan, which look plausible and hide the difference. In later assignments, as designing a modular search engine describes, query processing reached into the index's private preprocessing method to achieve the same guarantee.
What I would change: make the analyzer, the combination of tokenizer, filter, stop list, and stemmer, a separate object that is saved with the index. Any program that loads the index then also loads the exact analysis that built it. Queries pass through that one analyzer exactly once. This site's own search engine follows that rule: page text and query text go through the same function, as How This Search Works traces on its real index.
Representing postings
The index itself is a Python dictionary mapping each term to a set of docIDs:
for term in set(tokens):
self.index[term].add(doc_id)
Sets were a natural choice for the assignment. Python intersects them directly, which made the Boolean queries of the next assignment easy to implement. The representation has three consequences that the rest of the course makes visible:
- No order. Sets are unordered. The sorted-list merge described in intersecting postings lists, and the gap encoding that depends on sorted lists, cannot be applied without sorting first.
- No term frequencies. A set records only whether a term occurs in a document, not how often. The separate
term_frequencycounter records each term's collection frequency. That is enough to list the most frequent terms, but not the within-document frequencies that TF-IDF and BM25 need. When the vector space assignment arrived, the index had to be rebuilt to store frequencies. This was a direct instance of the principle from the architecture article that a ranking function can only use what the index stored, and of the table of posting contents in the inverted index. - Memory. Every Python object carries overhead. On a 64-bit build of CPython 3.13, the version these measurements were rerun with,
sys.getsizeofreports 28 bytes for a small integer, 64 for an empty dictionary, and 216 for a set containing a single integer. The figures differ between CPython versions. Most terms occur in only one or two documents, as Zipf's law predicts, so most of the index consists of tiny sets. A docID that would take 4 bytes as a raw integer, or one byte as a variable byte code, costs on the order of a hundred bytes in this representation.
The dictionary side has a consequence of its own. A Python dictionary is a hash table: it finds a term in constant expected time, and it cannot enumerate the terms that begin with a given prefix. A query such as mon* would need the terms in sorted order as well, or one of the indexes described in Wildcard Queries.
What I would change: store each postings list as a sorted array of integers with a parallel array of term frequencies, using Python's array module or NumPy, and convert to gaps with variable byte encoding when saving.
Measuring memory
The assignment required reporting the index's memory use. The code walks the index recursively, summing sys.getsizeof over every dictionary, set, and integer. It also reports the size of the index when serialized with pickle, labeled "Pickled (Compressed) Size".
The recursive measurement is the right approach for Python, since getsizeof alone reports only the outer container. The label describes the most visible effect, a smaller file, but pickle is a serialization format, not a compression method. The pickled index is smaller than the in-memory one mainly because it omits Python's per-object overhead. It is also smaller because pickle writes each small integer with a one-byte opcode followed by one or two bytes of value, a crude variable-length code of its own. Compressing it, with a general-purpose compressor such as gzip or with the integer codes of index compression, would shrink it much further.
The comparison between in-memory size, serialized size, and compressed size is itself instructive, and worth reporting as separate numbers. For the Reuters-21578 index built HW01's way, with 20,540 terms and 666,541 postings (sizes in megabytes, millions of bytes, rounded to two decimals):
| Representation | Size | Per posting |
|---|---|---|
Dictionary of sets, in memory (recursive getsizeof) |
44.50 MB | 67 bytes |
| Pickle of the same dictionary | 2.25 MB | 3.4 bytes |
| Pickle compressed with gzip, level 9 | 1.34 MB | 2.0 bytes |
| Postings as sorted 32-bit arrays (payload only) | 2.67 MB | 4 bytes |
| Postings as variable byte gaps (payload only) | 0.76 MB | 1.1 bytes |
The in-memory form is about sixty times the size of the variable-byte postings. Most of that is the fixed cost of a Python set for every term. 45.8 percent of the terms occur in only one story, and each of those pays more than two hundred bytes for a container holding a single docID. The last two rows count only the postings, not the dictionary of terms, so they understate a complete index somewhat. The 20,540 terms themselves add 124,199 characters, about 0.12 MB as a single string.
Saving and loading
The index is saved with pickle and can be exported to JSON for inspection. Pickle is convenient but has two drawbacks for anything beyond a course project:
- it is specific to Python;
- loading a pickle file can execute arbitrary code, so a pickled index should never be loaded from an untrusted source (Python Software Foundation, The Python Standard Library,
pickle).
A simple documented format, such as a dictionary file and a postings file of encoded integers, avoids both problems. It is also the form that the index construction algorithms naturally produce.
Building in parallel
The parallel mode divides the files into chunks, gives each chunk to a worker process with a starting docID, and merges the workers' partial indexes. It resembles the parsing phase of the distributed indexing described in index construction: workers parse their portions of the collection independently. MapReduce indexing partitions the work by term range and inverts each range in parallel. HW01 instead divides the work by document and merges all the partial indexes in a single process.
Each chunk receives a contiguous range of docIDs, so the merged postings could be kept in docID order if they were stored as sorted lists rather than sets. For a collection of a few thousand short files, the overhead of starting processes and transferring partial indexes between them can outweigh the gain. The benefit appears as collections grow. That is why the later assignments chose between sequential and parallel builds automatically, based on the number of documents.
Summary of changes
| Stage | HW01 | Revised |
|---|---|---|
| Decoding | UTF-8, invalid bytes silently dropped | UTF-8 with replacement, errors counted and reported |
| Document order | Directory listing order | Sorted filenames |
| Skipping files | Different rules in sequential and parallel builds | One shared rule |
| Token filter | Letters only | Explicit rules for punctuation, digits, apostrophes, and hyphens |
| Analysis | Rules duplicated in index and query parser; queries stemmed twice | Analyzer object saved with the index and applied once to each query |
| Postings | Set of docIDs | Sorted array of docIDs with term frequencies |
| Storage | Pickle | Documented format with gap and variable byte encoding |
None of these changes was needed to complete the assignment. Each becomes necessary once a collection outgrows a homework directory, and each corresponds to a principle from earlier in this topic.
Worked problems
These three problems are posed on HW01's own choices and are solved with the article's script, tools/experiments/indexing/pipeline_checks.py, which checks every answer. The course text's exercises on these subjects (Manning, Raghavan, and Schütze, 2008, chapters 1–2) are worked in the articles on the individual stages.
Problem 1. A file stores the word Zürich in Latin-1. Give its bytes, and what HW01's open(..., encoding='utf-8', errors='ignore') reads. Then give what errors='replace' reads, and what a reader that assumes Latin-1 makes of the same word stored in UTF-8.
Solution. The bytes are 5A FC 72 69 63 68. HW01 reads Zrich; with errors='replace' the result is Z�rich; and UTF-8 bytes read as Latin-1 give Zürich.
Latin-1 stores each of the six characters in one byte, and ü is FC. In UTF-8 a byte beginning with the bits 11111 cannot start any sequence, so FC, which is 11111100, is invalid wherever it stands. With errors='ignore' the decoder drops it and continues, leaving Zrich, a string that looks like a rare word and enters the index as one. With errors='replace' the decoder writes one replacement character, U+FFFD, in its place: Z�rich. Counting those characters, one here, is the report that the revised indexer makes. In the other direction, UTF-8 stores ü as the two bytes C3 BC, and Latin-1 assigns a character to every byte, so no error is raised at all: the reader sees à and ¼ and produces Zürich. Decoding the Latin-1 file as Latin-1 gives Zürich back intact, which is why the count of replacement characters is used to find the files that need another encoding.
Problem 2. Apply HW01's tokenizing line, without the stop list, to the newswire-style sentence U.S. oil prices rose 3.5 pct to $18.20 a barrel on Friday, OPEC's highest since mid-1986. Say which tokens survive, which are lost, and what terms are indexed.
Solution. NLTK's tokenizer produces 20 tokens, 12 survive the filter, and the indexed terms are oil, price, rose, pct, to, a, barrel, on, friday, opec, highest, sinc.
| Kind | Tokens | Count |
|---|---|---|
| Alphabetic, kept | oil, prices, rose, pct, to, a, barrel, on, Friday, OPEC, highest, since | 12 |
| Contain letters or digits, dropped | U.S., 3.5, 18.20, 's, mid-1986 | 5 |
| Pure punctuation, dropped | $ , . |
3 |
The tokenizer keeps U.S. and mid-1986 whole and splits OPEC's into OPEC and 's. isalpha() then rejects every token with a period, digit, apostrophe or hyphen in it. The sentence is about a price, and after filtering it contains neither of its two numbers, nor the year, nor the country. The stemmer lowercases and stems the twelve survivors: prices becomes price and since becomes sinc, and the rest are unchanged apart from case. Here 60 percent of the tokens are kept and 25 percent are dropped although they carry content, against 82.4 and 7.7 percent for the whole collection. The sentence was chosen to be dense with figures.
Problem 3. In the Reuters index built HW01's way, 9,401 of the 20,540 terms occur in a single story. Using the object sizes above, find what their sets cost in memory, and compare with the same postings as variable byte gaps.
Solution. The sets alone cost 2.03 megabytes, at least 108 times the variable byte postings. Each of the 9,401 terms has a set holding one docID, and a one-element set occupies 216 bytes: $9{,}401 \times 216 = 2{,}030{,}616$ bytes. That counts only the set objects, not the docID integers they point to or the dictionary's own entries for the terms. As a postings list, each of these terms has a single gap, the docID itself, which is at most 10,788 and so takes one or two bytes in a variable byte code: at most $9{,}401 \times 2 = 18{,}802$ bytes for all of them. The ratio is at least $2{,}030{,}616 / 18{,}802 \approx 108$. These single-story sets are 45.8 percent of the terms but only 4.6 percent of the 44.50 megabytes. The rest is the sets of the other terms, the term strings, the docID integers and the dictionary itself, which together bring the average to 66.8 bytes per posting.
What we have learned
A working indexer makes every decision this topic describes, often in a single line. On Reuters-21578, HW01's choices showed what each decision does at scale:
errors='ignore'drops undecodable bytes without a trace;isalpha()removes 7.7 percent of the tokens, most of them numbers;- a second stemming pass changes the stems of 3.8 percent of the distinct words;
- a dictionary of sets spends about sixty times the bytes of variable-byte postings.
The indexer then becomes the foundation for the Boolean retrieval assignment that follows. The next topic begins with The Boolean Retrieval Model, which establishes how a system answers a query that combines terms with AND, OR, and NOT from the index built here.
References
- Bird, S., Klein, E., and Loper, E. (2009). Natural Language Processing with Python. O'Reilly Media. record
- Lewis, D. D. (1997). Reuters-21578 text categorization test collection, distribution 1.0. record · 11 pages
- Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, chapters 1–2. Cambridge University Press. record · 102 pages
- Python Software Foundation. The Python Standard Library:
pickle,array, andsys.getsizeof. https://docs.python.org/3/library/ record · 2 pages
Reviewed: verified, 16 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 11 revisions