Skip to main content

duplicate-client-records-python-uae-clinic

Updated 6 min readMarkdown

Disclosure: I used AI to help draft this article. I wrote and ran the code and tests myself. I work at an accounting software partner in Dubai, and this is a general programming tutorial.

UAE businesses are moving to structured electronic invoices, and a business-to-business invoice needs the buyer's tax registration number. For a clinic, that raises a data question. The customer list holds corporate clients that pay for employee health checks, insurers, and suppliers, and over the years the same company often gets entered twice. "Alpha Medical Supplies LLC" and "Alpha Medical Supplies L.L.C." are one business, but a computer sees two.

This post builds a small Python tool that finds likely duplicates in a client list, and flags two kinds of tax number conflict. It decides nothing. It produces a short list for a person to review.

The three checks

  1. Similar names. Two names that look like the same business, after removing company-type words such as LLC or Ltd.
  2. Same tax number, different names. One number attached to two different businesses.
  3. Same name, different tax numbers. One business with two numbers.

The code

import csv
import re
import sys
from collections import defaultdict
from difflib import SequenceMatcher
from itertools import combinations

# Words that describe the type of company, not which company it is.
LEGAL_WORDS = {"llc", "fze", "fzco", "fz", "ltd", "limited", "co",
               "company", "inc", "est", "establishment"}


def normalize(name):
    """Lowercase, drop dots and punctuation, and remove company-type words."""
    text = name.lower().replace(".", "")
    text = re.sub(r"[^a-z0-9 ]", " ", text)
    return " ".join(w for w in text.split() if w not in LEGAL_WORDS)


def similar_pairs(records, threshold=0.88):
    """Return pairs of names that look like the same business."""
    keyed = [(r["name"], normalize(r["name"])) for r in records]
    pairs = []
    for (name_a, key_a), (name_b, key_b) in combinations(keyed, 2):
        score = SequenceMatcher(None, key_a, key_b).ratio()
        if score >= threshold:
            pairs.append((name_a, name_b, round(score, 2)))
    return pairs


def tax_number_conflicts(records):
    """Return tax numbers that are used by more than one distinct name."""
    names_by_trn = defaultdict(set)
    for r in records:
        trn = r.get("trn", "").strip()
        if trn:
            names_by_trn[trn].add(normalize(r["name"]))
    return {t: sorted(n) for t, n in names_by_trn.items() if len(n) > 1}


def name_conflicts(records):
    """Return business names that appear with more than one tax number."""
    trns_by_name = defaultdict(set)
    for r in records:
        trn = r.get("trn", "").strip()
        if trn:
            trns_by_name[normalize(r["name"])].add(trn)
    return {n: sorted(t) for n, t in trns_by_name.items() if len(t) > 1}


if __name__ == "__main__":
    with open(sys.argv[1], newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    print("Possible duplicates:")
    for a, b, score in similar_pairs(rows):
        print(f"  {a} | {b} ({score})")
    print("Same tax number, different names:")
    for trn, names in tax_number_conflicts(rows).items():
        print(f"  {trn}: {names}")
    print("Same name, different tax numbers:")
    for name, trns in name_conflicts(rows).items():
        print(f"  {name}: {trns}")

The matching uses SequenceMatcher from Python's standard library. You can read how it scores two strings in the difflib documentation.

Why normalise first

Without the normalize step, "Alpha Trading LLC" and "Alpha Trading L.L.C." score lower than you would expect, because the company-type words and the dots count as differences. Removing them makes the comparison about the part of the name that identifies the business. The word list is the part you will edit most.

Try it

Save a file called clients.csv. The names and numbers below are made up:

name,trn
Gulf Corporate Health LLC,100111111111111
Gulf Corporate Health L.L.C.,100111111111111
Alpha Medical Supplies,100222222222222
Alpha Medical Suplies,
Desert Insurance Services,100333333333333
Harbour Logistics FZE,100333333333333
Northern Dental Co.,100444444444444
Northern Dental Company,100555555555555

Run it:

python find_duplicates.py clients.csv

The output:

Possible duplicates:
  Gulf Corporate Health LLC | Gulf Corporate Health L.L.C. (1.0)
  Alpha Medical Supplies | Alpha Medical Suplies (0.98)
  Northern Dental Co. | Northern Dental Company (1.0)
Same tax number, different names:
  100333333333333: ['desert insurance services', 'harbour logistics']
Same name, different tax numbers:
  northern dental: ['100444444444444', '100555555555555']

Each line is a question for a person. The Gulf entries are probably one business typed twice. The Alpha pair looks like a typo, and one record has no tax number. The Desert and Harbour records share a number, so at least one entry is wrong. The Northern Dental records look like one business with two numbers.

The tests

from find_duplicates import (name_conflicts, normalize, similar_pairs,
                             tax_number_conflicts)


def rec(name, trn=""):
    return {"name": name, "trn": trn}


def test_normalize_removes_company_type_and_punctuation():
    assert normalize("Alpha Medical Supplies L.L.C.") == "alpha medical supplies"
    assert normalize("ALPHA MEDICAL SUPPLIES LLC") == "alpha medical supplies"


def test_same_business_written_two_ways_is_found():
    pairs = similar_pairs([rec("Alpha Medical Supplies LLC"),
                           rec("Alpha Medical Supplies L.L.C.")])
    assert len(pairs) == 1 and pairs[0][2] == 1.0


def test_typo_is_found_but_stays_below_perfect():
    pairs = similar_pairs([rec("Alpha Medical Supplies"),
                           rec("Alpha Medical Suplies")])
    assert len(pairs) == 1 and pairs[0][2] < 1.0


def test_different_businesses_are_not_flagged():
    assert similar_pairs([rec("Alpha Medical Supplies"),
                          rec("Gulf Corporate Health")]) == []


def test_same_tax_number_with_different_names_is_a_conflict():
    rows = [rec("Alpha Trading", "100111111111111"),
            rec("Beta Logistics", "100111111111111")]
    assert list(tax_number_conflicts(rows)) == ["100111111111111"]


def test_same_business_with_two_spellings_is_not_a_tax_conflict():
    rows = [rec("Alpha Trading LLC", "100111111111111"),
            rec("Alpha Trading L.L.C.", "100111111111111")]
    assert tax_number_conflicts(rows) == {}


def test_same_name_with_different_tax_numbers_is_flagged():
    rows = [rec("Alpha Trading LLC", "100111111111111"),
            rec("Alpha Trading L.L.C.", "100222222222222")]
    assert list(name_conflicts(rows)) == ["alpha trading"]


def test_blank_tax_numbers_are_ignored():
    rows = [rec("Alpha Trading"), rec("Beta Logistics")]
    assert tax_number_conflicts(rows) == {} and name_conflicts(rows) == {}

Notice the test for two spellings with the same number. Without normalising, the tool would report it as a conflict, which would be a false alarm.

Limits worth knowing

  • Similar is not the same. Two different businesses can have near-identical names. Treat every result as a question, never as a merge instruction.
  • The word list is a starting point. "Trading" and "Services" describe the business and are kept on purpose, but your data may need other words removed.
  • It compares every pair. That is fine for a few thousand records, but it slows down on very large lists. A blocking step, such as grouping by first letter, helps there.
  • Short names behave oddly. Two short names can score high on a single letter.
  • Keep patient data out of this file. A client list should hold business names and numbers only.

Takeaways

  • Normalise before you compare.
  • Treat matching as a way to build a review list, not to decide.
  • Test the false-alarm cases as carefully as the hits.
  • Check for conflicts in both directions, name to number and number to name.

If you adapt this to your own data, I would like to hear which company-type words you had to add.

About the author

  • Perfonec Computers specialises in accounting and financial management software and is an official partner of Sage 50, QuickBooks, Tally ERP, Zoho Books, and Odoo ERP. We also stand out as one of the best cloud hosting providers, offering reliable solutions for seamless business operations. Our ERP accounting solutions help you create budgets, monitor spending, and access comprehensive financial information.

No comments yet. Be the first to comment.