The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Extract hashtags and mentions from tweets

To extract hashtags and mentions from tweets, you can use simple regular expressions. Here’s how you can do it in Python:

python
import re def extract_hashtags_mentions(tweet): hashtags = re.findall(r'#w+', tweet) mentions = re.findall(r'@w+', tweet) return hashtags, mentions # Example tweet = "Excited to launch our new product! 🚀 Follow us @OpenAI and use #AI #MachineLearning to join the conversation!" hashtags, mentions = extract_hashtags_mentions(tweet) print("Hashtags:", hashtags) print("Mentions:", mentions)

Output:

vbnet
Hashtags: ['#AI', '#MachineLearning'] Mentions: ['@OpenAI']

This function:

  • Extracts hashtags using #w+, which matches # followed by one or more word characters.

  • Extracts mentions using @w+, which matches @ followed by one or more word characters.

Would you like this to work across a list of tweets or in another programming language?

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About