Sub topic 10
Extracting and Counting Hashtags with Code
This chapter assumes you can read basic Python (functions, lists, dictionaries, loops) and that you know what a hashtag is and why people choose them, as covered in the earlier chapters on hashtag mechanics and hashtag selection. You will build a small script that pulls hashtags out of post text, normalizes them, and counts them. You will also meet the edge cases that break naive versions.
Why count hashtags at all
Counting hashtags turns a pile of captions into a table you can read. Typical uses:
- Auditing your own posts to see which tags you actually use, as opposed to which you think you use.
- Comparing your tags with those of a competitor or a community, using captions you can see publicly or export from your own analytics.
- Spotting accidental variants, such as
#Coffee,#coffee, and#coffe, that split what should be one tag.
The script does not tell you how a platform ranks anything. It only describes text. Treat its output as an input to the decisions in the hashtag selection and measurement chapters.
The extraction model
A hashtag in plain text is a # followed by a run of word characters. Extraction needs three decisions:
- Where a tag starts. A
#begins a tag only if it is not glued to a preceding word character. Without this rule,C#or a URL fragment likepage#sectionwould produce false tags. - Where a tag ends. A tag ends at the first character that is not a letter, digit, or underscore. Punctuation such as
.,,,!, and spaces end it. - How to compare tags. Platforms generally treat hashtags as case-insensitive when searching, so the script lowercases tags before counting. Python's
casefold()is a stricter, Unicode-aware version oflower().
Step 1: 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 parts:
(?<!\w)is a negative lookbehind. It means "the character before this point is not a word character." It stops the match insideC#orabc#tag.#matches the literal hash sign.(\w+)captures one or more word characters.findallreturns only the captured group, so the#is dropped.
The output keeps order and duplicates. That is deliberate: the list still records that coffee appeared twice in this caption.
Step 2: Count across many posts
from collections import Counter
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)]Counter is a dictionary subclass that maps each item to how many times it was seen. most_common(n) returns the top n pairs, sorted by count. When two tags tie, as here, they appear in the order they were first seen.
Both snippets use the same extract_hashtags function, so run them in one file or one session. Put the import lines at the top and the function before the counting code.
Counting tags versus counting posts
The count above is a count of occurrences. If a caption repeats #coffee three times, the tag scores three. Often you want the number of posts that use a tag, which is what a comparison between accounts needs. Converting each post's tags to a set before counting gives that:
from collections import Counter
def extract_hashtags(text):
import re
return [t.casefold() for t in re.findall(r"(?<!\w)#(\w+)", text)]
posts = [
"#Coffee #coffee #COFFEE all day",
"Cold brew #coffee",
"Tea time #tea",
]
occurrences = Counter(t for p in posts for t in extract_hashtags(p))
posts_using = Counter(t for p in posts for t in set(extract_hashtags(p)))
print(occurrences.most_common())
# [('coffee', 4), ('tea', 1)]
print(posts_using.most_common())
# [('coffee', 2), ('tea', 1)]Occurrences say coffee appeared four times. Posts-using says two posts carried it. The second number is usually the fairer measure of how widely a tag is used, because one repetitive caption cannot inflate it. Repeating a tag in one caption is also a spam signal in the etiquette sense, so seeing a large gap between the two numbers is worth a look.
Edge cases that break naive extraction
A simple pattern works on tidy examples. Real captions are messier.
| Input | Naive result | What to decide |
|---|---|---|
| `C# tips` | May produce a tag if there is no lookbehind | The lookbehind rule rejects it |
| `see example.com/page#top` | `top` | The lookbehind rejects it, because `e` precedes `#` |
| `#2024goals` | `2024goals` | Digits are word characters, so this counts as a tag |
| `#1` | `1` | Digit-only tags are often not treated as hashtags by platforms; filter them if you care |
| `#café` | `café` | `\w` matches accented letters in Python 3 strings |
| `#Coffee,#Tea` | `coffee`, `tea` | A comma ends the first tag, and `#` after it is not preceded by a word character |
| `#coffee#tea` | `coffee` only | The second `#` follows a word character, so it is rejected |
| `#coffee-lovers` | `coffee` | The hyphen ends the tag; the rest is plain text |
| `##coffee` | `coffee` | The second `#` is preceded by `#`, which is not a word character |
Two of these deserve comment.
Digit-only tags. Platforms differ on whether #1 is clickable. This script does not know. If you want to mirror a given platform, add a filter after extraction and test it against what you see in the app:
def extract_hashtags_strict(text):
tags = [t.casefold() for t in re.findall(r"(?<!\w)#(\w+)", text)]
return [t for t in tags if not t.isdigit()]Concatenated tags. Writing #coffee#tea is a typing error that platforms may or may not repair. The script follows one clear rule and reports only coffee. If your data has many such cases, you will undercount, so check a sample by eye.
Unicode and normalization
casefold() handles case differences across languages better than lower(). For example, the German ß folds to ss. Accents are a separate problem. é can be stored as one character or as e plus a combining accent mark, and the two look identical but compare as different strings. Normalizing to a standard form first fixes this:
import re
import unicodedata
HASHTAG = re.compile(r"(?<!\w)#(\w+)")
def extract_hashtags(text):
text = unicodedata.normalize("NFC", text)
return [tag.casefold() for tag in HASHTAG.findall(text)]
composed = "#caf\u00e9"
decomposed = "#cafe\u0301"
print(extract_hashtags(composed) == extract_hashtags(decomposed))
# TrueWithout NFC normalization, those two captions would count as different tags. One more caveat: \w does not match every character that platforms allow in tags. Combining marks in some scripts, and emoji, fall outside \w, so tags in some languages can be cut short. If you work in such a language, test with real examples before trusting counts.
Reading data from a file
In practice you will have a spreadsheet or export rather than a Python list. A CSV export with a caption column can be processed like this:
import csv
import re
import unicodedata
from collections import Counter
HASHTAG = re.compile(r"(?<!\w)#(\w+)")
def extract_hashtags(text):
text = unicodedata.normalize("NFC", text)
return [tag.casefold() for tag in HASHTAG.findall(text)]
def count_from_csv(path, column="caption"):
counts = Counter()
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
counts.update(set(extract_hashtags(row[column] or "")))
return counts
if __name__ == "__main__":
import sys
for tag, n in count_from_csv(sys.argv[1]).most_common(10):
print(f"{n:4d} #{tag}")Run it as python count_tags.py posts.csv. Notes on the design:
counts.update(set(...))counts posts using each tag, not occurrences.row[column] or ""guards against empty cells, whichcsvreturns as empty strings but some exports return asNone.encoding="utf-8"avoids platform-dependent decoding errors with emoji and accents. If your export came from a spreadsheet program, it may have a byte-order mark; useutf-8-sigin that case.
Only process data you are entitled to use: your own exports, or content you are permitted to analyze under the platform's terms. Do not scrape accounts to build this table.
Reading the output
A table of counts is a description, not a verdict. Keep these limits in mind:
- A high count for a tag shows that it is common in your sample. It does not show that the tag drives discovery.
- A tag used by every competitor is probably broad and crowded. A tag used by one is either niche or irrelevant, and the counts alone cannot tell which.
- Variant spellings show up as separate rows. Scan the tail of the list for near-duplicates such as
cafelifeandcafe_life, and decide which one your audience actually searches. - To judge results, return to each platform's own analytics, as covered in the measurement chapter.
A readable tag for output and display
One more use of code: checking your own multi-word tags for readability. Capitalizing each word helps readers and screen readers split the words:
Harder to read aloud: #sundaycoffeeclub
Easier to read aloud: #SundayCoffeeClubYou can detect tags that are entirely lowercase and longer than a chosen length, then review them by hand:
def long_lowercase_tags(raw_text, min_len=12):
raw_tags = re.findall(r"(?<!\w)#(\w+)", raw_text)
return [t for t in raw_tags if t.islower() and len(t) >= min_len]
print(long_lowercase_tags("Join #sundaycoffeeclub and #SundayCoffeeClub #tea"))
# ['sundaycoffeeclub']This check must run on the original text, before casefold(), because normalization throws away the capitalization you want to inspect. The script flags candidates only. It cannot know where the word breaks belong, so you fix them yourself.
Common errors
- Counting after forgetting to normalize.
#Coffeeand#coffeeappear as two rows. Fix: applycasefold()inside the extraction function, not in the counting step. - Forgetting the lookbehind. Strings like
C#and URL fragments create false tags. - Using
findallwith two groups. If you add a second capturing group to the pattern,findallreturns tuples instead of strings. Use(?:...)for non-capturing groups. - Mixing occurrence and post counts. Decide which you mean before comparing two accounts.
- Treating the count as a recommendation. The script describes text. Choice of tags comes from intent and relevance.
Exercise
Write a function top_tags(posts, n) that returns the n most common hashtags by number of posts that use each tag (not total occurrences), lowercased. Then say what top_tags(["#A #a #a", "#a #b", "#b"], 2) returns and why.
Show answer
Code: import re from collections import Counter def toptags(posts, n): counts = Counter() for post in posts: tags = {t.casefold() for t in re.findall(r"(?<!\w)#(\w+)", post)} counts.update(tags) return counts.mostcommon(n) The call returns [('a', 2), ('b', 2)]. Post 1 contributes 'a' once, because the set removes the repeats. Post 2 contributes 'a' and 'b'. Post 3 contributes 'b'. So 'a' appears in two posts and 'b' appears in two posts. The tie keeps first-seen order, so 'a' comes first. Counting occurrences instead would give 'a' as 4 and 'b' as 2.
Exercise
The caption "Loving C# and #Coffee, see site.com/page#top #2024goals" is passed to the extraction function with the lookbehind pattern. Which tags does it return, and which two substrings are correctly rejected?
Show answer
It returns ['coffee', '2024goals']. The substring "#" in "C#" is rejected because the "C" before it is a word character. The "#top" in "site.com/page#top" is rejected because the "e" before the "#" is a word character. "#2024goals" is accepted because digits are word characters and the "#" follows a space.