Sub topic 3
Preparing review text: cleaning, deduplication and PII redaction
Every later step in a feedback analysis reads the text you prepare here. Sentiment scores, clusters and LLM prompts all inherit its problems. This chapter covers three jobs: cleaning text, removing duplicates, and redacting personally identifiable information (PII). PII is any detail that can identify a person, such as an email address or phone number.
It assumes you know basic Python, including regular expressions at the level of reading a pattern. It also assumes you have a list of review strings from the sources discussed in the previous chapter.
Why preparation comes first
Raw feedback is messy in ways that change your results:
- A review copied into three channels counts as three voices, so one angry customer can look like a trend.
- A review containing a phone number, once sent to an external LLM API, has already left your control.
- HTML fragments, odd whitespace and emoji variants split identical words into different tokens, which weakens TF-IDF and clustering.
Order matters. Redact before you send text anywhere outside your own systems. Normalise before you compare text for duplicates. Keep the original raw text in a protected store so you can audit decisions, and pass only prepared text downstream.
Step 1: Normalise the text
Normalising means turning different spellings of the same characters into one form. Typical problems in review data:
- HTML entities such as
&and leftover tags from web scraping. - Unicode variants, such as a non-breaking space or a full-width letter, that look identical but compare as different.
- Runs of whitespace, line breaks and control characters.
- Truncated or empty entries, such as a review that is only "." or "N/A".
Python's standard library covers most of this:
import html
import re
import unicodedata
TAG = re.compile(r"<[^>]+>")
CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")
def normalise(text):
text = html.unescape(text)
text = TAG.sub(" ", text)
text = unicodedata.normalize("NFKC", text)
text = CONTROL.sub(" ", text)
return re.sub(r"\s+", " ", text).strip()
print(normalise("Great phone <br> works fine\u00a0!"))Run this and you get Great phone works fine !. NFKC is a Unicode normalisation form that maps compatibility characters, such as the non-breaking space, to their plain equivalents.
Be careful about what you do not clean. Do not lowercase, strip punctuation or remove stop words at this stage. Sentiment models and LLMs use capitalisation ("TERRIBLE"), exclamation marks and negations ("not good"). Aggressive cleaning belongs inside a specific method, such as the TF-IDF vectoriser, and not in the shared preparation step.
Step 2: Redact PII
PII shows up in reviews more often than people expect. Customers write "email me at ...", paste order confirmations, or sign their name at the end. Redaction replaces each detected item with a placeholder such as [EMAIL]. The placeholder keeps the sentence readable and tells later steps that something was there.
The spine's first example does this for emails and phone numbers with two regular expressions:
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 +44 20 7946 0958 or write to [email protected]"))The output is Call [PHONE] or write to [EMAIL].
What regular expressions miss and over-catch
Regex redaction is a baseline, not a guarantee. Know its failure modes before you rely on it.
| Problem | Example | Effect |
|---|---|---|
| False positive on numbers | Order number `1234 5678 90` or a date range `2024-11-01 2024-11-26` | Useful text is replaced by `[PHONE]` |
| Missed phone formats | `five five five, oh one two three` | Number stays in the text |
| Names | "Hi, I'm Maria Lopez from Leeds" | Not detected by either pattern |
| Addresses and IDs | "14 Mill Lane", a card number, a customer ID | Not detected unless you add patterns |
| Obfuscated emails | `jane dot doe at example dot com` | Not detected |
For names, locations and addresses you need named entity recognition (NER), a model that tags spans of text as person, place or organisation. Libraries such as spaCy and Microsoft Presidio provide NER-based PII detection. You can also add domain patterns of your own, such as your order-ID format, so those IDs are redacted on purpose and not by accident.
Choose your error direction deliberately. For text that will leave your systems, prefer over-redaction: losing a date is cheaper than leaking a phone number. For text that stays inside, favour precision so you keep usable content.
Redact before you deduplicate
Redaction should come first, for two reasons. It collapses reviews that differ only in the personal details, so they match during deduplication. And no later step, including logging, ever sees the original value. Never log raw review text in the preparation step itself; log counts and IDs.
Step 3: Deduplicate
Duplicates distort counts. If a theme appears in 300 reviews but 120 are copies, you will overstate it by about 67%. Duplicates come in several kinds, and each needs a different tool.
| Kind | Cause | Detection |
|---|---|---|
| Exact | Same review exported twice, or a double-submitted form | Hash or string equality |
| Normalised | Differ only in case, spacing or redacted details | Compare cleaned, lowercased text |
| Near-duplicate | A few words changed, often by copy-paste or bots | Similarity measure on word sets or vectors |
| Same author, different text | One person writes five reviews | Author or device ID, not text |
The spine's deduplicate function handles the first two kinds. It builds a key from the cleaned, lowercased text and keeps the first review for each key:
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()
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 phone! Contact me at [email protected]",
"great phone! Contact me at [email protected]",
"Call +44 20 7946 0958 about my refund",
]
print(len(deduplicate(reviews)))This prints 2. The first two reviews have different email addresses and different capitalisation, but after cleaning they share the same key.
A leak in the example
Look at what deduplicate returns: unique.append(review) stores the original review, so the raw email address is still in the output. That is fine if you only want counts, but not if the result feeds an LLM. In a real pipeline, return the cleaned text instead:
def prepare(reviews):
seen = set()
prepared = []
for review in reviews:
cleaned = clean_review(review)
key = cleaned.lower()
if key and key not in seen:
seen.add(key)
prepared.append(cleaned)
return preparedThe key and test also drops reviews that are empty after cleaning. This version assumes clean_review from the previous block is defined.
Near-duplicates
Exact matching misses "Great phone, fast delivery!" next to "Great phone, fast delivery :)". A common approach is Jaccard similarity: the size of the shared word set divided by the size of the combined word set. You flag pairs above a threshold, often between 0.8 and 0.9, for review or removal. Comparing every pair costs O(n²), so for large sets use MinHash with locality-sensitive hashing (available in the datasketch package), which finds likely matches without comparing everything.
Do not deduplicate too aggressively. Short reviews such as "Love it" or "Too expensive" are legitimately repeated by different people. If many customers independently write the same short sentence, collapsing them hides real signal. Two safeguards help:
- Only deduplicate across the same author or source when the text is shorter than some minimum length, for example 5 words.
- Keep a count of how many copies each retained review had. A column such as
copieslets you report both "unique voices" and "total mentions".
Choosing what to keep
Preparation should be a function you can rerun, with its choices written down. At minimum, record for each batch:
- how many reviews came in and how many went out
- how many were dropped as empty, exact duplicates and near-duplicates
- how many redactions of each type were made
A sudden change in these numbers is an early warning. If the redaction count falls to zero after a source changes its export format, your patterns may no longer match the new layout.
Common mistakes
- Deduplicating before redacting. Reviews that differ only in personal details stay separate.
- Storing the original in the deduplicated output. The PII survives into later steps.
- Lowercasing everything early. You lose emphasis that sentiment methods use. Use a lowercase key for comparison only, as the example does.
- Trusting a regex as complete. Test it against a sample of real reviews and read what it missed.
- Language assumptions. The patterns above assume Western email and phone formats. Multilingual feedback needs patterns and NER models for each language.
Check your understanding
Exercise
A teammate changes the pipeline so that deduplicate() runs on the raw reviews first, and clean_review() is applied afterwards to the survivors. Name two problems this causes in the results.
Show answer
First, reviews that differ only in the PII or whitespace (for example the same text with two different email addresses) are not recognised as duplicates, so they are all kept and counts are inflated. Second, the key comparison happens on raw text, so personal data is processed and may be stored in the deduplication set before it is redacted. Redacting and normalising first fixes both.
Exercise
Your regex phone pattern replaces "order 1234 5678 90 arrived late" with "order [PHONE] arrived late". Give one way to reduce this false positive and one risk of the change.
Show answer
Add a negative check or a more specific pattern, for example require a leading "+" or a known country or area-code structure, or exclude digit groups that follow the word "order". The risk is that real phone numbers in unexpected formats are no longer redacted and leak into later steps, so test against a sample and consider over-redaction when text leaves your systems.