Sub topic 3
Preparing review text: cleaning, deduplication and PII redaction
This chapter assumes you know basic Python (lists, sets, functions, regular expressions at a simple level) and have the goals and label taxonomy from the first chapter in hand. Raw reviews are messy, repeated and sometimes personal. Fixing that before any analysis keeps later results honest and keeps personal data out of every downstream step.
Why preparation comes first
Three problems show up in almost every review set:
- Noise. Extra spaces, line breaks, stray markup and inconsistent casing make identical text look different to a program.
- Duplicates. The same review can be exported twice, posted on several sites, or pasted by a bot. Duplicates inflate counts, so a theme looks more common than it is.
- Personal data. Reviews and support messages often contain email addresses, phone numbers and names. PII (personally identifiable information) is data that can identify a person. If it reaches a clustering job, a prompt or a shared report, you have spread it further than you intended.
The order matters. Redact first, then deduplicate on the cleaned text, then pass the result on.
Cleaning and redacting
The function below replaces emails and phone numbers with placeholder tokens, then collapses runs of whitespace into single spaces.
import re
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
PHONE = re.compile(r"\+?\d[\d\s().-]{7,}\d")
def clean_review(text):
text = EMAIL.sub("[EMAIL]", text)
text = PHONE.sub("[PHONE]", text)
return re.sub(r"\s+", " ", text).strip()
print(clean_review("Call me on +44 20 7946 0958\nor write to [email protected] please"))This prints Call me on [PHONE] or write to [EMAIL] please. Placeholders are better than deleting the text. A sentence such as "email me at [EMAIL]" still reads naturally, and it tells you a contact request was made.
What regular expressions miss
Patterns catch structured identifiers. They do not catch names ("Ask for Maria at the Leeds branch"), street addresses, order numbers or account IDs, and they can over-match. The phone pattern above will also match a long run of digits such as a tracking number. Treat the result as a first filter, not a guarantee. For names and addresses, add a named-entity recognition (NER) model, which labels people, places and organisations in text, or ask your team whether an existing redaction service is approved for use. Then sample the output by hand.
Deduplicating
Exact duplicates are easy to find if you compare a normalised key. Lower-casing and cleaning the text before comparison means "Great product" and "great product" count as one review.
def deduplicate(reviews):
seen = set()
unique = []
for review in reviews:
key = clean_review(review).lower()
if key not in seen:
seen.add(key)
unique.append(review)
return unique
reviews = [
"Great product!",
"great product!",
"Arrived late, mail me at [email protected]",
"Arrived late, mail me at [email protected]",
]
print(len(deduplicate(reviews)))The output is 2. The last two reviews differ only by email address, and because the key is built after redaction, they collapse into one. That is the reason for redacting before deduplicating.
The function returns the original text of the first copy, not the cleaned text. In a real pipeline, return the cleaned text for anything that leaves the restricted store.
Limits of exact matching
Exact matching misses near-duplicates, such as a review with one extra sentence, or the same text translated or lightly reworded. Two common options exist:
| Approach | Catches | Cost |
|---|---|---|
| Exact match on cleaned text | Copy-paste repeats, double exports | Very cheap |
| Near-duplicate match (for example, shingle overlap or embedding similarity above a threshold) | Light rewording, bot templates | Needs a threshold you must tune |
Start with exact matching and record how many reviews it removed. A large drop is itself a finding, since it can point to a data export bug or a review campaign.
Common errors
- Deduplicating before redacting. Reviews that differ only in personal details stay separate.
- Overwriting the original. Keep raw text in restricted storage so you can fix a bad rule later.
- Removing too much. Stripping punctuation, emoji or negations ("not good") can change sentiment. Clean for consistency, not for brevity.
- Silent deletion. Log how many reviews each step changed or removed, so results can be explained later.
Exercise
A teammate runs deduplication first and redaction second. Give one concrete way the output differs from running redaction first, using two reviews that are the same except for an email address.
Show answer
With deduplication first, the two reviews have different raw text, so both are kept. After redaction both contain "[EMAIL]" and are identical, so the duplicate count is too high and the theme looks more frequent than it is. Redacting first makes both reviews map to the same key, so only one is kept.
Exercise
The phone pattern matches a 12-digit tracking number in a review. Name one way to reduce this false positive and one reason you might still accept some false positives.
Show answer
Tighten the pattern, for example by requiring a recognisable phone format or country prefix, or by checking the surrounding words. You might accept some false positives because wrongly redacting a number loses little information, while missing a real phone number exposes personal data.