Do you need the raw dump? If all you want is the plain text of the articles, somebody has already done this: there are cleaned-up copies of Wikipedia published as ready-made datasets, and you should use one. The raw dump is for when you want what those throw away: the links between articles, the categories, the templates and tables, the redirects, or a copy from this month rather than last year.
Would you benefit from GBs of organized text that can be categorized into hierarchies of domains and subject matter silos? Keep reading.
Feeding The Text Analysis Beast
Wikipedia is a great source of organized text1, useful for language projects2. In addition to the exposition style used in many articles, there are many tables of details and facts, along with the valuable relationships between articles, categories, and emergent ontologies.
While training or augmenting large language models is the most obvious use, developing and testing word embeddings, sentiment analysis, fact extraction, or solutions containing combinations of those facets3, having large volumes of text to run through the system is a benefit.
Wikipedia conveniently provides regularly updated dumps of their corpus. In this case I’m focused on the English language articles extract which you can find at https://dumps.wikimedia.org/enwiki/4, along with the correlating index file for the same.
Wikipedia is imperfect and its many faults have been well documented, but it remains an extraordinary resource.
As of November 2026, the English articles extract and its correlating index file sum to a rounded 27GB in bzip2 form. There is no need to decompress, though if you did they would expand to about ~100GB.
Other extracts are available, such as the entire revision history of articles, media, and other languages, however the focus here is the current (or as current as the extract) revision text of English language articles.
For this exercise I’m going to work with the 20261101 (November 1st, 2026) variant, though the process I describe has remained the same for years.
The two files I am working with now are enwiki-20261101-pages-articles-multistream.xml.bz2 and enwiki-20261101-pages-articles-multistream-index.txt.bz2. Hashes (sha1, md5) are linked to on the download page. Verify your files before wasting your time dealing with a potentially corrupt download.
This is an intro to acquiring, processing, and making sense of those extracts, then beginning the initial analysis, at which point the reader can specialize to their own particular needs. I’m using Python purely because it’s the tool that I was using in other parts of the analysis chain for this particular project (given its strong machine learning tooling). However, it would be easy to do the same thing in any number of other stacks. This isn’t language advocacy, and I make no claims of being a python expert5.
Notes on BZIP2
These extracts are compressed with bzip2. bzip2 is not a file archiver and does not store more than one file or any metadata about the same. It is merely a compressed sequence of bytes, offering a better compression ratio than many competitors6 at the cost of increased compression time. When the need requires more than one file or file metadata to be preserved, the norm is to tarball first, then feeding that output to bz2 (e.g. .tar.bz2), however for the wiki use each is a single file. A massive XML file for the main articles dump, along with a separate colon-delimited index file.
Bzip2 supports a feature called “streams”: several complete bzip2 files joined end to end, the decompression of which will be the concatenated sum. If you took two separate files and bzip2 compressed them, then concatenating the results (e.g. cat file1.txt.bz2 file2.txt.bz2 > file3.txt.bz2, or copy /b on Windows), that would be a multistream bzip2 file, and when decompressed would yield a single file that would be the combination of the two files, end to end. While many formats would use a head or tail metadata block detailing each of these segments for easier processing/interpretation, bzip2 does not.
Wikipedia makes use of those streams — note the “multistream” in the filenames — offering the benefits of parallelization to both compression and decompression stages. It allows them to split the articles into sets of 100 and then compress each bundle independently and in parallel. When complete they can combine them in order, documenting the offset of each in a separate index file. This benefit carries to consumers of the file which can selectively decompress parts of the stream surgically, or can parallelize processing the file for performance reasons, which is the approach discussed here.
The Index File
The index file tells us in which bz2 “stream” of the larger bz2 file a particular article can be found by telling us the byte offset to the beginning of that discrete bz2-compressed segment. In the uncompressed index file (though we stream decompress it during processing, so you don’t need to decompress it in advance) you’ll find millions of lines of text in the form of
Offset:ArticleId:ArticleName
e.g.
566:10:AccessibleComputing
The offset is the bytes from the beginning of the compressed file where the page, and up to 99 of its peers, can be found in an isolated bzip2 stream, the result being a partial XML document.
The dump begins with various bookkeeping and administrative type metadata, hence why the first article is several hundred bytes in.
Here is the start of the real file, laid out the way it sits on disk.
You’ll notice that a series of articles will share the same offset because articles were combined into the same bzip2 stream. If you wanted to surgically extract a single article you would need to decompress the stream from the offset (to the next offset or the end of the file) and then parse the resulting XML to find the specific article you seek among the 1007 in that set.
A Note On The Python Code
This isn’t a python tutorial. I’m not trying to teach anyone about command line arguments, robust error handling or optimized python. My error approach for this is “if something small fails, fail entirely because human intervention is necessary”. I wrote this entry after trying to solve a simple need8, finding online instructions that were wrong (or wrong-headed) in various time-wasting ways. Hopefully this one proves valuable to visitors, and I will periodically update it to reflect changes in the wiki dumps and the necessary tooling.
I’m going to hardcode paths for the code for simplicity, but you shouldn’t do this in your own code. I trust the reader has the capacity to adapt code to their own environment. I’ve removed code comments9.
Processing The Index File
The only use for the index file in this scheme is to find all the unique offsets, allowing for the parallel processing of the separate streams from the larger file. In the scenario being discussed I am working with the index file enwiki-20261101-pages-articles-multistream-index.txt.bz2.
I could eliminate the need for the index file by pre-scanning the larger file, finding the beginning and end of each stream, but bz2 is a non-trivial format. For instance the end of stream magic sequence (0x177245385090) isn’t byte aligned. Normal lazy mechanisms fail without a much more involved interpretation of the file, which I have no interest in building.
Wikipedia provides the index file. Even though 99% of it is redundant if we want just the offsets, it’s a robust, simple source, and ultimately is a tiny amount of processing for a lot of benefit. If you were looking to find and extract a single article you could use the additional data in the index file to do so.
Let’s make some code to extract the unique offsets from the index file. In the case of the 20261101 file there are 259,950 offsets, covering 25,991,252 pages. Note that this code caches the results, drawing from the cache on subsequent runs. If you’re like me you’ll probably decide to change how you process the files and re-run multiple times, so having this pre-extracted is beneficial.
A set is used for the initial extraction, eliminating duplicates10. It is then sorted into a list and returned to the caller.
wikiindex.py
import bz2
import os
def process_index_file(index_source, persist=True):
cache = index_source + ".offsets"
if os.path.exists(cache):
with open(cache) as cached:
return [int(line) for line in cached]
stream_offsets = set()
with bz2.open(index_source, "rt", encoding="utf-8") as index:
for line in index:
stream_offsets.add(int(line.split(":", 1)[0]))
sorted_stream_offsets = sorted(stream_offsets)
if persist:
with open(cache, "w") as cached:
cached.write("\n".join(map(str, sorted_stream_offsets)))
return sorted_stream_offsets
This code could be called from another module via a call like
import wikiindex
offsets = wikiindex.process_index_file("./enwiki-20261101-pages-articles-multistream-index.txt.bz2")
About twenty seconds to process, and assuming you haven’t passed False to persist, immediate on subsequent calls. The caching file is about 3MB in size.
Using The Offsets To Process The Article Dump
Now that we have the offsets, let’s process them in parallel. For this we’re going to leverage the multiprocessing package. If you attempt to do this using threads you’re going to quickly hit a scalability ceiling given the limits of GIL11, which is fine given that the multiprocessing facilities comes at little overhead for our purposes, while being very easy to utilize. We will also be using the xml.sax package for the data extraction from the XML fragments.
This solution approach uses little memory while offering high degrees of parallelism and great efficiency.
In this example I’ve also leveraged the wikitextparser dependency (e.g. pip install wikitextparser) as it works well for my needs. It extracts the plain-text in addition to all the internal and external links within the page (in the wikilinks and external_links list members, respectively), and I’ve found it a great kick-start to extracting value from the wiki dump.
To help with the comprehension of the following code, it effectively performs the following steps-
-
Load the discrete set of offsets described in the prior section regarding the index file. This tells us where each distinct bz2 “file” is in the total archive
-
Start a pool of worker processes, one per core, each opening the dump for itself
-
Hand the offsets to the pool a few at a time, to whichever worker is free. Originally I pre-assigned an equal number of offsets to each process, however in a world of asymmetrical cores (efficiency, performance), and the reality that each offset contains sets of articles of varying complexity, a shared pile of work is better12.
-
Each worker decompresses the bz2 content found at its offset into an XML fragment, which is wrapped in a root element to make a valid XML document
-
It uses a SAX parser to iterate over that XML document, pulling each discrete page efficiently, calling a process function on each successful extract
-
Whatever that function returns goes back to the main process, which does the printing
It helps to see what one of those pages looks like. This is the second page in the file, trimmed:
<page>
<title>Anarchism</title>
<ns>0</ns>
<id>12</id>
<revision>
<id>1383011684</id>
<timestamp>2026-10-31T14:20:33Z</timestamp>
<contributor>...</contributor>
<model>wikitext</model>
<text bytes="114197" xml:space="preserve">{{Short description|Political philosophy and movement}} ...</text>
</revision>
</page>
ns is the namespace: 0 is an ordinary article, and the dump also carries templates, category pages, help pages and the rest, each with its own number. There are two ids, the page’s and the revision’s, which is why the code checks which element it is inside. A redirect has a redirect element naming its target and almost no text.
In my case I use those extracts for a variety of analysis stages, along with populating the relationships and ontologies of all articles into a graph. That code has been removed as it isn’t necessary for this article, and in its place the sample pulls out the two things a graph is built from: what each article links to, and the categories it is filed under.
wikiprocess.py
import bz2
import io
import multiprocessing
import xml.sax
import wikitextparser
import wikiindex
articles_source = "./enwiki-20261101-pages-articles-multistream.xml.bz2"
index_source = "./enwiki-20261101-pages-articles-multistream-index.txt.bz2"
ARTICLE_NAMESPACE = 0
# this is a placeholder. Presumably you would do something more useful
def your_function(page_id, page_ns, page_title, page_redirect, page_content):
if page_ns != ARTICLE_NAMESPACE or page_redirect is not None:
return None
parsed = wikitextparser.parse(page_content or "")
targets = [link.title.strip() for link in parsed.wikilinks]
categories = [target[9:] for target in targets if target.startswith("Category:")]
return page_id, page_title, len(targets) - len(categories), categories
class PageHandler(xml.sax.ContentHandler):
def __init__(self):
super().__init__()
self.results = []
self.read_stack = []
self.text_aggregate = []
self.in_page = False
def startElement(self, tag_name, attributes):
self.text_aggregate = []
if tag_name == "page":
self.page_id = None
self.page_ns = None
self.page_title = None
self.page_redirect = None
self.page_content = None
self.in_page = True
elif tag_name == "redirect" and self.read_stack[-1] == "page":
self.page_redirect = attributes["title"]
self.read_stack.append(tag_name)
def characters(self, content):
if self.in_page:
self.text_aggregate.append(content)
def endElement(self, tag_name):
self.read_stack.pop()
element_string = "".join(self.text_aggregate)
if tag_name == "page":
self.in_page = False
# We have the whole page so do with it what you will
result = your_function(self.page_id, self.page_ns, self.page_title, self.page_redirect, self.page_content)
if result is not None:
self.results.append(result)
elif self.in_page:
parent = self.read_stack[-1]
if parent == "page":
if tag_name == "title":
self.page_title = element_string
elif tag_name == "id":
self.page_id = int(element_string)
elif tag_name == "ns":
self.page_ns = int(element_string)
elif parent == "revision" and tag_name == "text":
# the actual page contents exist as a revision
self.page_content = element_string
dump = None
def open_dump():
# runs once in each worker process, so each has its own file handle
global dump
dump = open(articles_source, "rb")
def process_stream(stream_offset):
dump.seek(stream_offset)
decompressor = bz2.BZ2Decompressor()
output = [b"<pages>"]
while not decompressor.eof:
compressed = dump.read(65536)
if not compressed:
raise EOFError("The dump ends partway through the stream at {}".format(stream_offset))
output.append(decompressor.decompress(compressed))
output.append(b"</pages>")
handler = PageHandler()
xml.sax.parse(io.BytesIO(b"".join(output)), handler)
return handler.results
def main():
stream_offsets = wikiindex.process_index_file(index_source)
if not stream_offsets:
raise Exception("Index file unsuccessful")
articles = 0
with multiprocessing.Pool(initializer=open_dump) as pool:
for results in pool.imap_unordered(process_stream, stream_offsets, chunksize=4):
for page_id, page_title, link_count, categories in results:
articles += 1
print("{}: {} links, in {}".format(page_title, link_count, categories[:3]))
print("{} articles from {} streams".format(articles, len(stream_offsets)))
if __name__ == "__main__":
main()
This code has been significantly modified from my “production” source for illustrative purposes. Obviously you wouldn’t hard code file paths like this, for instance. Additionally the function your_function, called for each extracted and processed wiki article, is left as a placeholder.
process_stream seeks to the offset it has been given, bz2 decompresses from there until it hits a bz2 EOF, and runs an XML SAX extraction on the resulting fragment. If the file runs out first, the download was cut short, and it says so rather than waiting for ever.
PageHandler gathers the relevant data points for each Page element, and on a full successful extraction passes them to the user-defined function. In the sample that skips anything that isn’t an ordinary article, parses the wikitext, and returns the links and categories13.
What Comes Out
Run against the first twelve streams of the file, which is 1,200 pages, it prints 892 articles. The other 308 are redirects. A few of them:
Anarchism: 655 links, in ['Anarchism', 'Anti-authoritarianism', 'Anti-capitalism']
Albedo: 177 links, in ['Land surface effects on climate', 'Climate change feedbacks', 'Climate forcing']
Alabama: 994 links, in ['Alabama', '1819 establishments in the United States', 'Contiguous United States']
Achilles: 679 links, in ['Greek mythological heroes', 'Kings of the Myrmidons', 'Achaean Leaders']
Abraham Lincoln: 593 links, in ['Abraham Lincoln', '1809 births', '1865 deaths']
Every one of those links is an edge and every category is a rung on a ladder. That is the organized hierarchy promised at the top.
A full extraction of tens of millions of articles is still a fairly onerous task, and presumably you’re going to be doing intensive processing on the extracts (for instance building a graph from the wikilinks associations between each of the pages), but this approach is efficient and can saturate even a beastly machine, yielding the full benefit of vertical scalability. With a small amount of work it can be adapted for horizontal scalability.
Footnotes
-
the entire Gutenberg library can be downloaded as another easy source ↩
-
assuming you abide by the copyright considerations ↩
-
the classic SOLR style literal search is no longer competitive — search needs a contextual awareness and domain knowledge now ↩
-
there are unofficial torrents which transfer incredibly quickly but tend to be delayed from the official dumps. At time of writing they are over a month behind ↩
-
Like so many in this field, I am constantly jumping between different languages, stacks, and so on. I regularly have to hit the LLM to remind myself of basic best practices in toolings that I’ve used for years to decades ↩
-
though xz is much better at the cost of exponentially worse compression times ↩
-
the current standard is 100 articles per stream, at least until the final set containing the sub-100 remainder, however as good programmers we accommodate variations and assume it’s n ↩
-
a need for a large volume of test data for a system with an ontological structure for some LLM work ↩
-
I’m a huge fan of code comments to the greatest extent possible, as the work I’m involved in often means I’m revisiting my own code some time later and comments are a fantastic way of getting back to speed ↩
-
the index files have thus far been ordered, but failing to find any guarantees of that I’m going to treat it as hostile and assume that it can come in any order. It’s easy enough in a situation like this to code defensively ↩
-
Python 3.13 added a build without the GIL, experimental at first, however I still prefer the multiprocess approach for this, especially given how heavy processing each set of articles is for most scenarios ↩
-
An earlier version of this entry shared the work through a
multiprocessing.Queuefilled before the workers started. That works on Linux and hangs for ever on macOS, where a queue holds at most 32,767 items and a dump has a quarter of a million offsets. The pool has no such limit, and needs neither the queue nor the lock that went with it. ↩ -
worth noting that the print in the sample will significantly slow down the processing if running this as is to evaluate estimated performance ↩