Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the hashtags on twitter using python?

Tags:

python

hashtag

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"

like image 822
iCezz Avatar asked May 02 '26 04:05

iCezz


1 Answers

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('#')]
like image 174
Karl Knechtel Avatar answered May 03 '26 18:05

Karl Knechtel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!