Fixed-Size Chunking with Overlap in Python
Fixed-size chunking cuts text into pieces of roughly equal length, with a little overlap between neighbours. It is the simplest strategy, it is easy to reason about, and for uniform plain text it is often good enough. This post builds one in Python, explains its settings and shows where it breaks.
A word-based chunker
Counting words is a decent approximation of length when you do not want a tokenizer. The function slides a window over the words. Each step moves forward by size - overlap words, so consecutive chunks share overlap words.
def chunk_words(text: str, size: int = 200, overlap: int = 40) -> list[str]:
if overlap >= size:
raise ValueError("overlap must be smaller than size")
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
piece = words[start:start + size]
if piece:
chunks.append(" ".join(piece))
if start + size >= len(words):
break
return chunks
text = " ".join(f"word{i}" for i in range(1, 501))
parts = chunk_words(text, size=200, overlap=40)
print(len(parts)) # 3
print(parts[0].split()[-1]) # word200
print(parts[1].split()[0]) # word161
With 500 words, size 200 and overlap 40, the step is 160. The first chunk covers words 1 to 200, the second starts at word 161 (so words 161 to 200 appear twice), and the third covers words 321 to 500. The loop stops once a window reaches the end, which avoids a final chunk that is only overlap.
Keeping source information
A chunk that has lost its origin is hard to cite. Return a small record with the document ID, a chunk number and the character offsets if you need to highlight the passage.
def chunk_document(doc_id: str, text: str, size=200, overlap=40):
records = []
for i, piece in enumerate(chunk_words(text, size, overlap)):
records.append({
"id": f"{doc_id}:{i}",
"doc_id": doc_id,
"position": i,
"text": piece,
})
return records
The ID format docid:number makes it simple to delete all chunks of a document when it changes: remove everything whose doc_id matches.
Choosing size and overlap
- Size. Start around 150 to 300 words for prose and test. Stay below the embedding model's input limit.
- Overlap. Use 10 to 20 percent of the size. Zero overlap risks cutting an idea in two. Above 30 percent mostly adds duplicates.
- Content type. FAQs and glossaries need smaller chunks. Narrative or legal text may need larger ones.
Where fixed-size chunking breaks
- It can cut in the middle of a sentence, a code block or a table.
- It ignores headings, so a chunk may start with "Step 4" and never mention what product it belongs to.
- It splits whitespace-poor languages badly. Chinese and Japanese text has no spaces, so
text.split()returns one giant word. Use a tokenizer or split by characters or sentences for those languages. - It treats all text equally, so a heading and a paragraph have the same weight.
A sentence-aware improvement
A cheap upgrade is to pack whole sentences until you reach the size, instead of cutting at an exact word. This version uses a simple regular expression for sentence endings. It is not perfect for abbreviations like "e.g." but works for most prose.
import re
def chunk_sentences(text: str, max_words: int = 200) -> list[str]:
sentences = re.split(r"(?<=[.!?])\s+", text.strip())
chunks, current, count = [], [], 0
for s in sentences:
n = len(s.split())
if current and count + n > max_words:
chunks.append(" ".join(current))
current, count = [], 0
current.append(s)
count += n
if current:
chunks.append(" ".join(current))
return chunks
Every chunk now ends at a sentence boundary. A single sentence longer than max_words still becomes its own chunk, which is acceptable.
Testing your chunker
Chunkers are easy to get subtly wrong, so write a few tests. Check that no chunk is empty, that no chunk is larger than the limit, that joining the non-overlapping parts reproduces the original text, and that the overlap is exactly what you configured. An off-by-one error in the step size can silently drop words at the end of every document, and you would never see it in the final answers.
def test_chunker():
text = " ".join(str(i) for i in range(1000))
parts = chunk_words(text, size=100, overlap=10)
assert all(p for p in parts)
assert all(len(p.split()) <= 100 for p in parts)
assert parts[0].split()[-10:] == parts[1].split()[:10]
covered = set(w for p in parts for w in p.split())
assert covered == set(text.split())
test_chunker()
print("ok")
The last assertion is the important one: every word from the source must appear in at least one chunk. It protects you from losing content at the document tail.
When to use it
Use fixed-size chunking for a first prototype, for uniform text such as transcripts, and as a baseline to compare against fancier strategies. If structure exists in your documents, the next post shows how to use it.
Comments
No comments yet. Have a question or a tip? Be the first to share it.