排序 Tweepy Status 对象?

Sorting Tweepy Status objects?

我正在使用 Tweepy 获取热门话题列表。它基本上是转发次数最多的当前推文列表。当 API 对象 returns 我的推文列表时,我得到一个 Status 对象的列表。

我需要根据转推的数量对那些 Status 对象进行排序。 属性 是 retweet_count。我不知道如何正确执行,因为内置的排序方法不起作用,因为这是一个嵌套对象

这是我目前的情况:

def getTrendingTopics(self):

'''
Get popular tweets by getting current tweets.
Sort the tweets according to the number of retweets, from high to low. 
Return the 15 most popular tweets in a list.        
'''

      trendingTopicsList = {}
      publicTweets = self.api.home_timeline()

      for tweet in publicTweets:
           retweetCount = str(len(tweet.retweets()))
           ##Sort Tweets here?
           print(tweet.text + "\n Retweets: " + retweetCount + "\n")

        #return the tweets in a list

返回推文很容易,但我该如何对它们进行排序?

我尝试了几种方法,但 none 奏效了。我遗漏了那个代码。

感谢任何帮助。

只需使用 python sorted 将其应用于您的 tweet 对象。请参阅下面的玩具示例代码。

In [1]: 
class Tweet:
    def __init__(self, text, retweets):
        self.text = text
        self.rt = retweets

    def retweets(self):
        return self.rt

In [2]:    
t1 = Tweet("text1", 2)
t2 = Tweet("text2", 17)
t3 = Tweet("text3", 3)
l = [t1, t2, t3]
[t.text for t in l]

Out[2]:
['text1', 'text2', 'text3']

In [3]:    
from operator import methodcaller
lsorted = sorted(l, key=methodcaller('retweets'), reverse=True)
[t.text for t in lsorted]

Out[3]:
['text2', 'text3', 'text1']