Cleaning, Normalizing and Deduplicating Text
Remove boilerplate, fix encoding problems and drop exact and near-duplicate documents.
Extracted text is rarely clean. It contains broken characters, hyphenated line breaks, repeated boilerplate and duplicate documents. Every bit of noise ends up in your chunks, wastes embedding and LLM tokens, and can push the right answer out of the top results. This lesson builds a cleaning and deduplication step for the indexing pipeline.
Common problems in extracted text
| Problem | Example | Fix |
|---|---|---|
| Unicode variants | ?nance (ligature), full-width digits, non-breaking spaces | Unicode NFKC normalisation |
| Mojibake | donā??t instead of "don't" | The ftfy library |
| Hyphenated line breaks | informa-\ntion | Join the word |
| Hard line wraps | Every line ends mid-sentence | Join lines within a paragraph |
| Boilerplate | "Confidential - Page 3 of 20", cookie notices | Remove repeated lines and known patterns |
| Excess whitespace | Runs of spaces and blank lines | Collapse |
A cleaning function
pip install ftfy
import re
import unicodedata
import ftfy
BOILERPLATE = [
re.compile(r"^\s*page \d+( of \d+)?\s*$", re.I),
re.compile(r"^\s*confidential.*$", re.I),
re.compile(r"^\s*(all rights reserved|©).*$", re.I),
]
def clean_text(text: str) -> str:
text = ftfy.fix_text(text) # repair mojibake
text = unicodedata.normalize("NFKC", text) # ligatures, full-width chars
text = text.replace(" ", " ").replace("?", "")
# Drop boilerplate lines
lines = [l for l in text.splitlines() if not any(p.match(l) for p in BOILERPLATE)]
text = "\n".join(lines)
text = re.sub(r"(\w)-\n(\w)", r"\1\2", text) # informa-\ntion -> information
text = re.sub(r"(?<![.!?:\n])\n(?!\n)", " ", text) # join hard-wrapped lines
text = re.sub(r"[ \t]+", " ", text) # collapse spaces
text = re.sub(r"\n{3,}", "\n\n", text) # at most one blank line
return text.strip()
Line-joining rules can destroy lists, code and tables. Apply them only to prose, and skip documents that are already Markdown or structured output from a layout-aware parser.
Exact duplicates
The same file often exists in several places: a PDF and its copy in another folder, or the same FAQ on two web pages. Hash the normalised text and keep only the first copy.
import hashlib
def content_hash(text: str) -> str:
normalised = re.sub(r"\s+", " ", text.lower()).strip()
return hashlib.sha256(normalised.encode("utf-8")).hexdigest()
def remove_exact_duplicates(documents):
seen, unique = set(), []
for doc in documents:
h = content_hash(doc.text)
if h not in seen:
seen.add(h)
unique.append(doc)
return unique
Near duplicates
Near duplicates are more common: versions 1.2 and 1.3 of a policy that differ by one paragraph, or web pages with different navigation text. They crowd the top-k results with the same information. MinHash estimates the overlap (Jaccard similarity) between documents' word shingles quickly, and locality-sensitive hashing (LSH) finds similar pairs without comparing every pair.
pip install datasketch
from datasketch import MinHash, MinHashLSH
def shingles(text: str, n: int = 5) -> set[str]:
words = re.findall(r"\w+", text.lower())
return {" ".join(words[i:i + n]) for i in range(max(1, len(words) - n + 1))}
def minhash(text: str, num_perm: int = 128) -> MinHash:
m = MinHash(num_perm=num_perm)
for s in shingles(text):
m.update(s.encode("utf-8"))
return m
def remove_near_duplicates(documents, threshold: float = 0.85):
lsh = MinHashLSH(threshold=threshold, num_perm=128)
unique = []
for i, doc in enumerate(documents):
m = minhash(doc.text)
if lsh.query(m): # similar to a document we already kept
continue
lsh.insert(str(i), m)
unique.append(doc)
return unique
When near duplicates are versions of the same document, keep the newest one rather than the first one seen: sort the documents by date (newest first) before deduplicating.
Quality filters
Finally, drop documents that carry no useful information:
def is_useful(text: str, min_words: int = 30) -> bool:
words = text.split()
if len(words) < min_words:
return False
alpha_share = sum(c.isalpha() for c in text) / max(1, len(text))
return alpha_share > 0.5 # mostly letters, not numbers or symbols
Be careful with short documents in FAQ-style collections, where a 20-word answer can be exactly what users need. Tune the thresholds by looking at what gets dropped.
Putting it together
def prepare(documents):
for doc in documents:
doc.text = clean_text(doc.text)
documents = [d for d in documents if is_useful(d.text)]
documents = remove_exact_duplicates(documents)
documents = remove_near_duplicates(documents)
return documents
Key takeaways
- Normalise Unicode, repair encoding errors, fix hyphenation and remove boilerplate before chunking.
- Apply line-joining rules only to prose, never to code, lists or tables.
- Remove exact duplicates with a hash and near duplicates with MinHash LSH.
- Prefer the newest version when near duplicates are document versions.