Sub topic 3
Cleaning Noisy Text: URLs, Mentions, Hashtags, Emojis, and Casing
Assume you know basic Python, can install packages with pip, and understand training data, test data, and predictions. In this chapter, you will prepare reviews and social posts for sentiment analysis without removing useful emotional signals.
Why normalization needs care
Text normalization is the process of changing different forms of text into a more consistent form. Social posts often contain URLs, user mentions, hashtags, repeated spaces, emojis, and unusual capitalization.
Cleaning can help a model focus on meaningful words. However, aggressive cleaning can remove sentiment. For example, LOVE THIS!!! 😍 contains strong positive signals. Removing exclamation marks, emojis, and capitalization may make it look like the weaker sentence love this.
A useful rule is to replace information that is usually unique or distracting, while preserving information that may express opinion.
| Text element | Common treatment | Reason |
|---|---|---|
| URL | Replace with `<url>` | The exact address is rarely useful |
| Mention | Replace with `@user` | Usernames usually do not define sentiment |
| Hashtag | Remove `#`, keep the word | The hashtag word may carry meaning |
| Emoji | Keep it or convert it to a token | Emojis often express sentiment |
| Casing | Usually lowercase, preserve emphasis separately | Lowercase reduces duplicate features |
A conservative normalization function
Regular expressions are patterns used to find and replace text. The following function replaces URLs and mentions, removes the hash character from hashtags, and collapses repeated whitespace. It deliberately keeps punctuation and emojis.
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()
post = "Loving the new phone!! @shopfan #bestbuy https://example.com/x 😍"
print(normalize_post(post))The output is:
Loving the new phone!! @user bestbuy <url> 😍The replacement <url> gives every link a shared meaning. A classifier can learn that posts containing links behave differently without memorizing thousands of addresses. Replacing mentions also reduces the vocabulary size, which is the number of distinct tokens in the data.
Casing and emphasis
Lowercasing makes Great, GREAT, and great the same feature. This often improves generalization, especially when the training set is small.
Still, uppercase text can signal emphasis. You can preserve that information before lowercasing by adding a feature such as has_all_caps or uppercase_ratio. Repeated punctuation can be handled similarly.
def emphasis_features(text):
letters = [character for character in text if character.isalpha()]
uppercase_ratio = (
sum(character.isupper() for character in letters) / len(letters)
if letters else 0.0
)
return {
"has_all_caps": uppercase_ratio > 0.6 and len(letters) >= 4,
"exclamation_count": text.count("!"),
"uppercase_ratio": round(uppercase_ratio, 2),
}
print(emphasis_features("THIS IS AMAZING!!!"))Do not assume that every dataset needs these features. Test whether they improve validation performance.
Emojis and hashtags
Emojis can be kept as Unicode characters when your vectorizer supports them. Another option is to convert them into names such as :red_heart: or :crying_face:. Named tokens can be easier for some models to process, but conversion may lose details or introduce an extra dependency.
Hashtags often combine words, as in #BestBuy or #neveragain. Removing only # preserves the combined token. For more advanced processing, you can split camel case into best buy, but splitting can be wrong for brand names and abbreviations.
Normalization in a processing pipeline
A typical pipeline is:
Keep the original text as well as the normalized version. The original supports debugging and error analysis when a prediction seems wrong.
Exercise
Why should a sentiment pipeline usually replace a URL instead of deleting it completely?
Show answer
A placeholder such as <url> preserves the fact that a link appeared while avoiding a separate feature for every exact address.