Remove near-duplicate chunks with word shingles and Jaccard similarity

Why it matters Near-duplicate removal is a standard step when building RAG indexes and LLM training corpora from crawled data.

Crawled documents repeat boilerplate and lightly edited copies. Indexing them wastes space and fills the prompt with the same text twice.

Write near_dedupe(texts, n=3, threshold=0.8). For each text, take words = re.findall(r"[a-z0-9]+", text.lower()). Its shingle set is the set of all n-word tuples; if it has fewer than n words but at least one, the set holds the single tuple of all its words; an empty text has an empty set. Jaccard(A, B) = |A and B| / |A or B|, defined as 1.0 when both are empty. Keep a text if its Jaccard with every previously KEPT text is below threshold. Return the list of kept indices.

Signaturedef near_dedupe(texts, n=3, threshold=0.8)

Example

near_dedupe(["the cat sat on the mat", "The cat sat on the mat!", "a dog ran in the park"]) gives [0, 2].

Understand the idea

Exact matching misses most duplicates on the web: copies differ by a word, a punctuation mark or capitalisation. Shingling turns text into a set of overlapping word windows, so small edits change only a few elements. Jaccard similarity then measures overlap between two sets as shared elements over all distinct elements.

Example with 3-word shingles: "the cat sat on the mat" gives {the cat sat, cat sat on, sat on the, on the mat}. "The cat sat on the mat!" gives exactly the same set after lowercasing and dropping punctuation, so Jaccard = 4/4 = 1 and the copy is removed. "a dog ran in the park" shares nothing and is kept.

Rule: J(A, B) = |A intersect B| / |A union B|; keep a text if J < threshold against every kept text.

At web scale, MinHash approximates the same Jaccard score so that billions of documents can be deduplicated.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 5.

  • Sample 1: examplenear_dedupe(['the cat sat on the mat', 'The cat sat on the mat!', 'a dog ran in the park'])
  • Sample 2: subset textnear_dedupe(['refund policy: items can be returned within 30 days of delivery for a full refund', 'items ca...
  • Test 3: short textsnear_dedupe(['hi there', 'Hi, there', 'bye'], 3, 0.9)
  • Test 4: emptiesnear_dedupe(['', ' ', 'x y z'])
  • Test 5: lower thresholdnear_dedupe(['a b c d e f', 'a b c d e g', 'a b c x y z'], 2, 0.5)