Python 查找Twitter中最流行(转载最多)的10个Tweet


CODE:

#!/usr/bin/python 
# -*- coding: utf-8 -*-

'''
Created on 2014-7-4
@author: guaguastd
@name: find_popular_retweets.py
'''

# Finding the most popular retweets
def popular_retweets(statuses):
    retweets = [
                # Store out a tuple of these three values...
                (status['retweet_count'],
                 status['retweeted_status']['user']['screen_name'],
                status['text'])
                
                # ... for each status ...
                for status in statuses
                
                # ... so long as the status meets this condition.
                    if status.has_key('retweeted_status')
                ]
    
    return retweets
    
if __name__ == '__main__':

    # import login, see http://blog.csdn.net/guaguastd/article/details/31706155 
    from login import oauth_login

    # get the twitter access api
    twitter_api = oauth_login()
    
    # import search, see http://blog.csdn.net/guaguastd/article/details/35537781
    from search import search
    
    # pip install prettytable
    from prettytable import PrettyTable
    
    while 1:
        query = raw_input('\nInput the query (eg. #MentionSomeoneImportantForYou, exit to quit): ')
        
        if query == 'exit':
            print 'Successfully exit!'
            break
        
        statuses = search(twitter_api, query)
        retweets = popular_retweets(statuses)
        
        # Slice off the first 10 from the sorted results and display each item in the tuple
        pt = PrettyTable(field_names=['Count', 'Screen Name', 'Text'])
        [pt.add_row(row) for row in sorted(retweets, reverse=True)[:10]]
        pt.max_width['Text'] = 50
        pt.align = 'l'
        print pt

RESULT:

Input the query (eg. #MentionSomeoneImportantForYou, exit to quit): #MentionSomeoneImportantForYou
Length of statuses 32
+-------+----------------+----------------------------------------------------+
| Count | Screen Name    | Text                                               |
+-------+----------------+----------------------------------------------------+
| 1     | thuggie_salma  | RT @thuggie_salma: "@KillahPimpp:                  |
|       |                | #MentionSomeoneImportantForYou @thuggie_salma"     |
|       |                | baeee 




相关内容