Sub topic 10
Extracting and Counting Hashtags with Code
Prerequisites and goal
This chapter assumes you can write and run a small Python script and understand lists, functions, and loops. It also assumes you know that a hashtag is a word or phrase beginning with #.
The goal is to turn post text into normalized hashtag data. Normalization means converting equivalent forms into one consistent representation. For example, #Coffee and #coffee can both become coffee.
A regular expression, or regex, is a pattern used to find text. We will use one to find hashtags in captions, then count how often each tag appears.
Extract hashtags from one caption
import re
HASHTAG = re.compile(r"(?<!\w)#(\w+)")
def extract_hashtags(text):
"""Return hashtags in order, lowercased, without the leading #."""
return [tag.casefold() for tag in HASHTAG.findall(text)]
caption = "Fresh #Coffee at the #CafeLife meetup #coffee"
print(extract_hashtags(caption))
# ['coffee', 'cafelife', 'coffee']The pattern has three important parts:
#requires a literal hash character.(\w+)captures one or more word characters after the hash.(?<!\w)requires that the hash is not immediately preceded by another word character.
The negative lookbehind in (?<!\w) helps avoid treating part of word#tag as a normal hashtag. The parentheses create a capture group, so findall() returns only the tag text and not the leading #.
casefold() makes comparison more consistent than leaving capitalization unchanged. The function preserves the order of tags and preserves duplicates. That matters when you want to inspect the original use of tags.
Count hashtags across posts
A Counter is a dictionary-like Python object designed for frequency counts.
import re
from collections import Counter
HASHTAG = re.compile(r"(?<!\w)#(\w+)")
def extract_hashtags(text):
return [tag.casefold() for tag in HASHTAG.findall(text)]
posts = [
"Fresh #Coffee at the #CafeLife meetup",
"Cold brew tips #coffee #homebarista",
"Morning routine #CafeLife",
]
counts = Counter(tag for post in posts for tag in extract_hashtags(post))
print(counts.most_common(2))
# [('coffee', 2), ('cafelife', 2)]The nested generator reads as follows:
- Take one
postfromposts. - Extract its hashtags.
- Take each
tagfrom that result. - Give every tag to
Counter.
The result counts occurrences, not unique posts. If one caption repeats #coffee, that caption contributes two occurrences. If you need one count per post, convert each post's extracted tags to a set before updating the counter.
counts = Counter()
for post in posts:
counts.update(set(extract_hashtags(post)))
print(counts)
# Counter({'coffee': 2, 'cafelife': 2, 'homebarista': 1})Inspect the limits
This pattern intentionally uses a simple definition of a hashtag. It accepts letters, numbers, and underscores through \w. It does not include spaces, so #Sunday Coffee becomes sunday, not one multi-word tag. It also does not include every platform-specific rule, such as whether accented characters, emoji, or punctuation are supported.
Treat the output as an analysis aid rather than a platform's official parser. Test representative captions from the platform you are studying, and record any differences.
Exercise
What will extract_hashtags("Try #Tea, #tea, and word#hidden") return with the pattern in this chapter?
Show answer
['tea', 'tea']. The comma is not part of the tag, and the negative lookbehind excludes word#hidden.