When two lists of names refuse to match, the problem is rarely the matching logic. It is the text. One export says "Joe's Barber Shop " with a trailing space, another says "JOE'S BARBER SHOP", and a third has a curly apostrophe copied from a website. Python sees three different strings. A person sees one business.
I run into this constantly, whether I am merging spreadsheets for Local Flyer Ads or checking generated sample data during AI evaluation work. Over time I settled on a small normalization routine that I run before any comparison. Here is how it works and why each step is there.
Start with the obvious: whitespace and case
def basic_clean(text):
return " ".join(text.split()).casefold()
Calling split() with no arguments splits on any run of whitespace, including tabs and the non breaking spaces that sneak in from web pages, and it drops leading and trailing space. Joining with a single space collapses everything into one clean line.
I use casefold() instead of lower(). For plain English they behave the same, but casefold() is designed for caseless comparison and handles characters like the German ß correctly. It costs nothing to use the right tool.
Normalize Unicode so look alike characters really match
Copy and paste brings surprises: accented letters stored two different ways, full width characters, odd spaces. The unicodedata module fixes most of this.
import unicodedata
def unicode_clean(text):
return unicodedata.normalize("NFKC", text)
NFKC folds compatibility characters into their standard forms, so a full width "A" becomes a normal "A", and composed and decomposed accents end up identical. It does not turn curly quotes into straight ones, so I handle those separately.
Replace or remove punctuation on purpose
I keep a small translation table for characters I want to swap, then strip whatever punctuation is left.
import string
SWAPS = str.maketrans({
"’": "'",
"‘": "'",
"“": '"',
"”": '"',
"&": " and ",
})
DROP = str.maketrans("", "", string.punctuation)
def punctuation_clean(text):
return text.translate(SWAPS).translate(DROP)
str.translate is fast because it works character by character inside the interpreter. Turning "&" into " and " before dropping punctuation means "Smith & Sons" and "Smith and Sons" land in the same place.
Be deliberate here. Dropping punctuation is right for business names and wrong for email addresses or product codes. I write separate cleaners for those instead of one function that tries to do everything.
Put it together in the right order
Order matters. Unicode first, so the swaps see standard characters. Punctuation next. Whitespace and case last, because removing punctuation can leave double spaces behind.
def normalize(text):
if text is None:
return ""
text = unicode_clean(str(text))
text = punctuation_clean(text)
return basic_clean(text)
Converting with str() protects against numbers sneaking in from a spreadsheet, and returning an empty string for None keeps later code simple.
Keep the original next to the clean version
The biggest lesson I learned: never overwrite the original value. I store both.
records = [{"raw": name, "key": normalize(name)} for name in names]
The normalized key is for matching. The raw value is for showing people and for debugging when a match looks wrong. If I only keep the cleaned text, I cannot explain to anyone why two rows were treated as the same.
Check what collapsed together
Normalization can be too aggressive. Two genuinely different names might end up with the same key. A quick check catches that.
from collections import defaultdict
groups = defaultdict(set)
for r in records:
groups[r["key"]].add(r["raw"])
for key, raws in groups.items():
if len(raws) > 1:
print(key, sorted(raws))
I read through that output once before trusting the results. Most groups are exactly what I wanted. Every so often one reveals a rule that went too far, and I adjust the cleaner rather than patching the data by hand.
Test the cleaner with real examples
Because the cleaner is a plain function, it is easy to test.
def test_normalize():
assert normalize(" Joe’s Barber Shop ") == "joes barber shop"
assert normalize("SMITH & SONS") == normalize("Smith and Sons")
assert normalize("ABC") == "abc"
assert normalize(None) == ""
Every time a messy value surprises me, it becomes a new test case. The function gets a little smarter, and I never debug the same problem twice.
What I would tell someone starting out
Most matching problems are cleaning problems in disguise. Before reaching for fuzzy matching libraries or similarity scores, normalize whitespace, case, Unicode and punctuation, keep the original text, and look at what collapsed together. That small routine fixes the majority of mismatches I see, and it keeps the remaining hard cases visible instead of hidden.
Originally published at tonycantave.com by Tony Sterlin Cantave, a Connecticut software developer.
Top comments (0)