Sub topic 3
Cleaning Noisy Text: URLs, Mentions, Hashtags, Emojis, and Casing
What this chapter assumes
You should be comfortable with Python, regular expressions at a basic level, and the idea of a train/test split. You do not need to know TF-IDF or transformers yet. Later chapters cover those. This chapter explains how to prepare reviews and social posts so that the signal that carries sentiment survives and the noise does not.
Cleaning is a set of decisions
Generic preprocessing advice says to lowercase everything, strip punctuation, and delete anything that is not a letter. For sentiment analysis that advice does damage. Compare these two posts:
I LOVE this phone!!! 😍i love this phone
The first is more intense. The exclamation marks, the capitals, and the emoji are all evidence of sentiment. A cleaning step that removes them throws away information the classifier could use.
For each noisy element, choose one of three actions:
| Action | Meaning | Use when |
|---|---|---|
| Keep | Leave it unchanged | The model already knows how to use it |
| Replace | Swap it for a placeholder or a word | The category matters, but the exact value does not |
| Remove | Delete it | It carries no sentiment and adds noise |
The right choice depends on the model downstream. A lexicon tool such as VADER wants text close to the original. A TF-IDF classifier wants consistent tokens. A pretrained transformer expects text close to what it saw in training.
URLs
A link almost never carries sentiment, and every URL is unique, so each one becomes a rare token that the model cannot generalize from. Replace it with a placeholder such as <url>. Do not delete it silently. Posts that include a link often differ in style from posts that do not, such as news shares compared with personal opinions, and the placeholder lets a model learn that pattern.
A simple pattern is https?://\S+|www\.\S+. It will occasionally swallow a trailing period or closing parenthesis. For sentiment work that error is harmless.
Mentions
A handle such as @shopfan identifies a person or brand. The identity is rarely useful, and keeping it can cause leakage: if one angry customer posts hundreds of times, the model may learn that handle instead of the language. Replace every mention with @user.
There is one exception. If your task is about a specific brand, and the mention marks who the sentiment is aimed at, you might keep a placeholder like @brand for the target and use @user for everyone else. Aspect-based sentiment, covered in a later chapter, extends this idea.
Hashtags
A hashtag is a word with a # in front, and the word often carries the sentiment: #blessed, #fail, #NotHappy. Strip the # and keep the word. Hashtags written in camel case can also be split into separate words, so #NotHappy becomes Not Happy. The split matters because negation (Not) is easy to lose inside a single long token.
Long hashtags written in one case, such as #ilovemondays, need a word-segmentation library to split. Most pipelines skip that and accept the loss.
Emojis and emoticons
Emojis are often the strongest sentiment signal in a short post. Three strategies exist:
- Keep them as characters, if the downstream tokenizer handles them. Transformer tokenizers generally do, and VADER does.
- Convert them to words, such as
emoji_love. This works with tokenizers that would otherwise drop non-letter characters. - Remove them. This is rarely a good idea for sentiment.
Emojis can also contradict the text. Great, another delay 🙃 is probably negative. Do not hard-code an emoji's polarity into your cleaning step. Pass the emoji through as a feature and let the model learn its meaning from data.
Repeated letters and punctuation
People write sooooo good and noooo to show emphasis. Each spelling is a different token to a bag-of-words model, so they fragment the counts. Collapse any run of three or more identical characters down to two: sooooo becomes soo. Keeping two rather than one preserves a trace of the emphasis and avoids merging soo with the normal word so. The same rule shortens !!!!! to !!.
Casing
Lowercasing helps a bag-of-words model because Great, GREAT, and great become one feature. It also erases a real signal. ALL-CAPS words usually mean shouting, and VADER explicitly boosts the score of a capitalized sentiment word when other words in the text are not capitalized.
The compromise is to record the signal first and then lowercase:
- Count the all-caps words of three or more letters before lowercasing.
- Pass that count to the model as an extra feature, or ignore it if you use a model that does not need it.
- Skip the lowercasing entirely for case-sensitive pretrained models.
The three-letter minimum keeps words such as I, OK, and TV from counting as shouting. Acronyms like USB or NASA will still count, so treat the feature as a rough hint.
A complete cleaning function
The first function below is the minimal version from the plan. It replaces links and mentions, unpacks hashtags, and leaves punctuation and emojis alone.
import re
def normalize_post(text):
text = re.sub(r"https?://\S+", "<url>", text)
text = re.sub(r"@\w+", "@user", text)
text = re.sub(r"#(\w+)", r"\1", text)
return re.sub(r"\s+", " ", text).strip()
print(normalize_post("Loving the new phone!! @shopfan #bestbuy https://example.com/x"))This prints Loving the new phone!! @user bestbuy <url>. It is the right preparation for VADER or a transformer. The second version prepares text for a TF-IDF model, where consistent lowercase tokens matter and emojis would otherwise be discarded.
import re
URL_RE = re.compile(r"https?://\S+|www\.\S+")
MENTION_RE = re.compile(r"@\w+")
HASHTAG_RE = re.compile(r"#(\w+)")
SHOUT_RE = re.compile(r"\b[A-Z]{3,}\b")
REPEAT_RE = re.compile(r"(.)\1{2,}")
SPACE_RE = re.compile(r"\s+")
EMOJI_WORDS = {
"😍": "emoji_love",
"😀": "emoji_smile",
"😂": "emoji_laugh",
"😡": "emoji_angry",
"😢": "emoji_sad",
"👍": "emoji_thumbsup",
"👎": "emoji_thumbsdown",
}
def split_camel(tag):
return re.sub(r"(?<=[a-z])(?=[A-Z])", " ", tag)
def clean_for_model(text):
shouting = len(SHOUT_RE.findall(text))
text = URL_RE.sub(" <url> ", text)
text = MENTION_RE.sub(" @user ", text)
text = HASHTAG_RE.sub(lambda m: " " + split_camel(m.group(1)) + " ", text)
for char, word in EMOJI_WORDS.items():
text = text.replace(char, f" {word} ")
text = text.lower()
text = REPEAT_RE.sub(r"\1\1", text)
text = SPACE_RE.sub(" ", text).strip()
return text, shouting
raw = "I LOVE this phone sooooo much 😍 #BestBuy @shopfan https://x.co/a"
print(clean_for_model(raw))The output is ('i love this phone soo much emoji_love best buy @user <url>', 1). The second value is the shouting count, which you can feed to the model as an extra column.
Check the tokenizer that comes next
Your cleaning step and your tokenizer work together, and they can undo each other. The default tokenizer in scikit-learn's TfidfVectorizer uses the pattern (?u)\b\w\w+\b. That pattern:
- drops punctuation, so
<url>becomesurland@userbecomesuser - drops one-character tokens
- drops emojis, because they are not word characters
Dropping the angle brackets is fine, since url and user are still consistent tokens. Dropping emojis is the reason the TF-IDF function above converts them to words first. Exclamation marks also vanish, so any signal in !! is lost unless you supply a custom token_pattern.
Which model wants which cleaning
| Downstream model | URLs and mentions | Emojis | Casing | Punctuation |
|---|---|---|---|---|
| VADER lexicon | Replace or remove | Keep | Keep | Keep |
| TF-IDF plus logistic regression | Replace | Convert to words | Lowercase, keep a caps count | Mostly lost by tokenizer |
| Pretrained transformer | Replace | Keep | Follow the model's convention | Keep |
For pretrained models, check the model card. A model trained on tweets, such as the one used in a later chapter, was trained on text where links became http and mentions became @user. Matching that convention helps slightly. Heavy cleaning beyond it usually does not.
Edge cases
- A review may contain HTML entities such as
&or". Decode them withhtml.unescapebefore applying any pattern. - Quoted text inside a review (
The seller said "great condition" but it was broken) carries the opposite sentiment from the quoted words. Cleaning cannot fix this. It is a modeling problem, covered under linguistic challenges. - Texts in several languages need language-aware lowercasing and different emoji conventions. Do not assume English rules hold.
- Over-cleaning is harder to notice than under-cleaning. Compare your classifier's F1 score with and without each step. A step that does not help should go.
Exercise
A teammate lowercases all text and removes every character that is not a letter or space before running VADER on social posts. Name three kinds of sentiment evidence this removes, and give a better way to prepare text for VADER.
Show answer
The step removes capitalization emphasis (VADER boosts ALL-CAPS sentiment words), punctuation emphasis (VADER boosts the score for exclamation marks), and emojis and emoticons (VADER's lexicon scores them directly). A better preparation replaces only URLs and mentions with placeholders or removes them, collapses whitespace, and leaves casing, punctuation, and emojis untouched, as in normalize_post above.
Exercise
In cleanformodel, why is the all-caps count taken before the call to text.lower() instead of after it?
Show answer
After lowercasing, no word is in capitals, so the count would always be zero. The shouting signal exists only in the original casing, so it must be measured before that information is destroyed.