iCezz
iCezz

Reputation: 634

How to use the hashtags on twitter using python?

Can anyone tell me how to use retrieve hashtags from Twitter in Python? I have tried using:

test = api.GetUserTimeline()
for i in test:
    text = i.text
    hashtag = i.hashtags
    print text
    print "\n" + hashtag

It returns hashtag as None, while in the text it is "life is #wonderful"

Upvotes: 3

Views: 1958

Answers (1)

Karl Knechtel
Karl Knechtel

Reputation: 61643

As far as I can tell, the underlying Twitter API doesn't actually parse out hashtags for you, and neither does the python-twitter wrapper. (Of course, I didn't look very hard ;))

Fortunately, it's pretty easy to do this yourself. Hashtags are words that start with '#'; so we ask Python for each word that starts with '#', with that '#' removed (i.e., from the second character to the end of the word), where the words come from splitting the text into words. It's almost clearer in Python than in English:

 hashtags = [word[1:] for word in i.text.split() if word.startswith('#')]

Upvotes: 3

Related Questions