Wednesday, December 25, 2013

Application of Hashtags in Python

#hastags, seen almost all over the web. We see them on twitter, g+, facebook and lots of other websites around the world. After learning something about Regular Expressions, I thought to just develop a simple example showing the use of hashtags in python.

In this example, we are going to use a dictionary to map our Texts, or messages to various hashtags. But for this I recommend you to know about regular expressions. These might seem difficult when you first look at them. Well, at least I find them quite difficult myself. Through regular expressions, we are going to find the hashtag(s) in our message, make it(them) a key(s) in the dictionary and map it to the list of messages.

So, here is the code for doing the same:

import re
from collections import defaultdict
dic = defaultdict(list) #this is going to be our list
hatag = r'#\w+' #the RegEx we will match with
def addtext(string): #this functions adds messages to our dictionary
    hashtags = re.findall(hatag,string) #finds the hashtags
    for x in hashtags: 
        dic[x[1:]].append(string) #makes key-value pairs of hashtags and messages
def search(hashtag): #searches messages given on hashtags.
    return dic[hashtag]

You can download this module here: Mediafire Link

See also:
Programming Languages, Udacity: The first chapter of this course intros Python Regex really great