Sub topic 4
Cleaning, normalising and deduplicating the raw questions
This chapter assumes you can read short Python scripts and use regular expressions at a basic level. It also assumes you have already collected raw questions from sources such as support tickets, sales calls, search logs, community threads and reviews. Personal data is removed first, in the same pass as the cleaning described here. The aim is a list in which each distinct customer question appears once, in the customer's own wording, with a count of how often it was asked.
Why this step comes before labelling and clustering
Raw questions are messy. The same question arrives with different spacing, capital letters, signatures, greetings and typos. If you label or cluster that raw list, duplicates inflate some topics and hide others. Every later step (intent labels, clusters, sampling) uses the counts you produce here. Errors made here carry through to the final prompt set.
Cleaning has four jobs:
- Scrub personal data so it never reaches later steps.
- Strip noise that is not part of the question.
- Normalise text into a comparison key, without overwriting the original wording.
- Deduplicate on that key and keep a count.
The order matters. Scrub first, so the dedupe key and any stored text contain no personal data. Normalise second, so near-identical strings match. Count last, because counts are only valid once duplicates are merged.
Scrubbing personal data
Personal data is any detail that identifies a person, such as an email address, phone number, name, order number or street address. Replace each one with a placeholder that says what kind of detail it was. Placeholders keep the sentence readable. A question like "Can I change the email on order [ORDER]?" still tells you the customer's intent.
The script below handles the two most obvious patterns, emails and phone-like numbers. It then builds a comparison key and keeps the first original wording seen for each key.
import re
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
PHONE = re.compile(r"\+?\d[\d\s().-]{7,}\d")
def scrub(text):
text = EMAIL.sub("[EMAIL]", text)
return PHONE.sub("[PHONE]", text)
def normalise(text):
return re.sub(r"\s+", " ", text).strip().lower()
def clean_and_dedupe(questions):
seen = {}
for q in questions:
cleaned = scrub(q)
seen.setdefault(normalise(cleaned), cleaned)
return list(seen.values())Here is a short run so you can see the behaviour:
raw = [
"Can I move my subscription to a different email address?",
"can i move my subscription to a different email address?",
"Call me on +44 20 7946 0958 about my refund",
"Why was I charged twice? Contact [email protected]",
]
for item in clean_and_dedupe(raw):
print(item)The first two entries collapse into one, and the original capitalisation of the first one is kept. The third and fourth entries come out as "Call me on [PHONE] about my refund" and "Why was I charged twice? Contact [EMAIL]".
Check that your phone pattern does not eat legitimate numbers. A question such as "Does the plan include 1000 000 API calls?" could match a pattern that accepts spaces between digits. Test your patterns against real examples from your sources before you trust them.
Stripping noise
Noise is text that belongs to the channel, not to the question. Each source has its own kinds:
| Source | Typical noise | What to do |
|---|---|---|
| Support tickets | Greetings, signatures, quoted earlier replies, ticket footers | Remove the boilerplate lines; keep the customer's sentence |
| Sales call notes | Speaker labels, timestamps, filler words | Strip labels and timestamps |
| Search logs | Keyword fragments, repeated queries from one session | Keep as written; collapse repeats within a session |
| Community threads | Usernames, "+1" replies, quoted text | Drop replies that add no new question |
| Reviews | Star ratings, praise with no question | Keep only sentences that ask or imply a question |
Do not rewrite the question while stripping noise. Remove surrounding text, and leave the customer's words alone. Later chapters rely on that wording being intact, because the prompt set should sound like customers, not like your team.
A simple noise filter might drop greeting-only and signature lines before scrubbing:
import re
GREETING = re.compile(r"^(hi|hello|hey|dear [\w\s]+|thanks|thank you|regards|best)[,.! ]*$", re.I)
def strip_noise(text):
lines = [ln.strip() for ln in text.splitlines()]
kept = [ln for ln in lines if ln and not GREETING.match(ln)]
return " ".join(kept)
print(strip_noise("Hi,\nHow do I export my data?\nThanks"))This prints How do I export my data?.
Normalising: build a key, keep the original
Normalisation turns different spellings of the same text into one comparison form. The important design choice is to separate two things:
- The key is the aggressively normalised form used only to decide whether two questions match.
- The display text is the cleaned but otherwise untouched wording that you store and later use in prompts.
The normalise function above shows the minimum: collapse runs of whitespace, trim the ends and lower-case. You can extend the key with more steps, as long as each step does not merge questions that mean different things.
| Step | Example | Safe? |
|---|---|---|
| Collapse whitespace | `"a b"` becomes `"a b"` | Yes |
| Lower-case | `"Export"` becomes `"export"` | Yes, for most languages |
| Unicode normalisation (NFKC) | Curly quotes and full-width characters become plain forms | Yes |
| Strip trailing punctuation | `"cancel?"` becomes `"cancel"` | Usually |
| Remove stop words | `"how do I cancel"` becomes `"cancel"` | Risky, it can merge different questions |
| Stemming | `"cancelling"` becomes `"cancel"` | Risky, it can merge different questions |
A key with more steps merges more variants, and it also raises the chance of merging questions that differ in a way that matters. "Can I cancel?" and "Can I not cancel?" would collapse if you removed the word "not" as a stop word. Start with the safe steps, and add a risky one only after checking what it merges.
Here is a slightly stronger key that adds Unicode normalisation and trailing punctuation removal:
import re
import unicodedata
def make_key(text):
text = unicodedata.normalize("NFKC", text)
text = re.sub(r"\s+", " ", text).strip().lower()
return text.rstrip("?!. ")Deduplicating and keeping counts
The clean_and_dedupe function above throws away how many times each question appeared. That count is valuable. A question asked 37 times is a stronger signal of real demand than one asked once, and the sampling step later uses it. Keep it.
from collections import Counter
def dedupe_with_counts(questions):
first_seen = {}
counts = Counter()
for q in questions:
cleaned = scrub(q)
key = make_key(cleaned)
first_seen.setdefault(key, cleaned)
counts[key] += 1
return [
{"text": first_seen[key], "count": n}
for key, n in counts.most_common()
]This reuses scrub from earlier and make_key from the previous section. Each record has the shape you will extend in later chapters. By the end of the pipeline a record looks like this:
{"id":"q-0042","text":"Can I move my subscription to a different email address?","source":"support_tickets","intent":"how_to","cluster":"account_management","count":37}At this stage you only have text and count. Add id and source as you go. Keep the source, because the same question may come from several channels, and you may want to know which.
Counting across sources
When you merge sources, decide whether a duplicate in two sources counts as two. Usually it should. A question that appears in both support tickets and search logs is asked in more places. If one customer sends the same question five times in one thread, though, that is one need, not five. Where you can, deduplicate by customer and conversation first, then count across them.
Exact duplicates versus near duplicates
Everything above finds exact duplicates after normalisation. Customers also ask the same thing in different words:
- "How do I cancel my plan?"
- "How can I cancel my subscription?"
- "I want to stop my subscription"
These are near duplicates. Do not merge them in this chapter. Merging by wording similarity is clustering, and it belongs in a later step where you can inspect the groups. Different phrasings are also useful: they show how customers really talk. Keep them as separate records for now.
There is one case worth handling here: near-identical strings that differ only by a typo. A cheap check is to compare keys with a similarity ratio and review the pairs above a high threshold, rather than merging automatically.
from difflib import SequenceMatcher
def likely_typo_pairs(keys, threshold=0.93):
pairs = []
for i, a in enumerate(keys):
for b in keys[i + 1:]:
if SequenceMatcher(None, a, b).ratio() >= threshold:
pairs.append((a, b))
return pairsThis compares every pair, so it is quadratic and suits a few thousand questions at most. For larger sets, use a blocking step first (compare only questions that share their first few words), or use embeddings in the clustering step. Always review the pairs by hand. A ratio of 0.95 can pair "Does it support Python 3?" with "Does it support Python 2?", which are different questions.
Edge cases and common errors
- Questions with several parts. "How do I export my data and can I delete my account?" holds two needs. Keep it as written for now. You can split it when you label intent.
- Statements that imply questions. Reviews often say "Support never explained the refund policy." This implies a question about the refund policy. Decide with your team whether to keep such lines, and mark them with a source flag so you can filter them later.
- Non-English text. Lower-casing and punctuation rules differ by language. Detect the language and either process each language separately or set it aside. Do not deduplicate across languages with an English-only key.
- Case that carries meaning. Product names and acronyms, such as "IT" and "it", can change meaning. Lower-casing the key is acceptable. Keep the original case in the display text.
- Very short items. A search query like "refund" has no clear question. Keep it, but expect to label it carefully later.
- Over-merging from aggressive keys. If your record count drops sharply after adding a normalisation step, inspect a sample of merged groups before you accept it.
Checking the result
Before moving on, look at the output directly. These checks take a few minutes and catch most problems:
- Print the 20 most frequent questions. They should read as real, plausible customer questions, not boilerplate such as "Please see attached".
- Print 20 random questions. Look for leftover personal data, signatures and truncated text.
- Print 10 merged groups, with every original variant. Confirm each group means one thing.
- Compare counts to the source totals. The sum of
countshould equal the number of questions that survived the noise filter.
def sanity_check(records, survivors):
total = sum(r["count"] for r in records)
assert total == survivors, f"counts {total} do not match {survivors}"
for r in records:
assert "@" not in r["text"], f"possible email left in: {r['text']}"The @ check is a crude test. It catches only one kind of leak, so it supports the manual sample and does not replace it.
Exercise
Your cleaned list shows "Can I cancel?" and "Can I not cancel?" as a single record with a count of 52. Which normalisation step most likely caused this, why is it a problem for a prompt set, and how do you fix it?
Show answer
Stop-word removal most likely dropped the word "not", so both questions produced the same key. This is a problem because the two questions have opposite meanings, and the merged count of 52 overstates demand for one of them and hides the other. Fix it by removing stop-word removal from the key, or by keeping negations and similar meaning-bearing words in the key. Then re-run the dedupe and inspect a sample of merged groups to confirm that none of them mixes different meanings.
Exercise
Write a Python function keep_longest(records) that takes dictionaries with text and count fields and returns the record with the highest count, using the longer text as a tie-breaker. Then say why you might prefer the first-seen wording as the display text instead.
Show answer
Code: def keep_longest(records): return max(records, key=lambda r: (r["count"], len(r["text"]))). First-seen wording is often preferable because it is an actual customer's untouched phrasing, and it is deterministic if the input order is fixed. The longest variant may include extra context or noise that no single customer asked in that form, and picking it systematically biases the prompt set toward wordy text.