如何从Tweepy ResultSet中提取信息

时间:2017-03-01 21:24:03

标签: python tweepy

如何与Tweepy结果集进行交互?我如何提取信息?它有点像列表或字典,但我无法提取它的特定元素。

@keyframes example {
        0%    {border-color: #444444;}
        10%    {border-color: #4C4C4C;}
        20.0%  {border-color: #4C3333;}
        30.0%  {border-color: #660000;}
        40.0%  {border-color: #4C1919;}
        50.0%  {border-color: #990000;}
        60.0%  {border-color: #CC0000;}
        70.0%  {border-color: #FF0000;}
        100.0%  {border-color: #FF0000;}
    }
    .container-frame {
        position: absolute;
        border-style: solid;
        border-width: 5px;
        animation-duration: 0.5s;
        animation-name: example;
        animation-timing-function: step-end ;
        animation-iteration-count: infinite ;
        animation-direction: alternate ;
    }

我之前从未处理过像ResultSet这样的对象,所以我不确定如何从中提取信息。我注意到它有点像列表,因为我可以从列表中得到一条特定的推文:

import tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

print(type(api.favorites('twitter')))
Out[1]: <class 'tweepy.models.ResultSet'>

print(api.favorites('twitter'))
Out[2]: Status(favorited=False, source='Twitter for iPhone', in_reply_to_status_id=None, coordinates=None, text='Starting the Twitter chat now. https://t.co[...]

但我不能得到这样的嵌入式元素:

print(api.favorites('twitter')[1])

或者像这样:

print(api.favorites('twitter')[1][0])
Out[3]: TypeError: 'Status' object does not support indexing

感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

tweepy.ResultSetsubclass of a Python's list

class ResultSet(list):
    """A list like object that holds results from a Twitter API query."""

ResultSet中的元素可以是不同类型 - 状态,用户,关系等。

特定ResultSet中的每个元素都是Status instance,允许属性访问(通过点符号)到twitter状态属性:

result_set = api.favorites('twitter')
status = result_set[0]
print(status.favorited)

答案 1 :(得分:0)

在这里,我使用resultset循环显示了for。在for循环中,使用与提到的@alecxe相同的方式来访问每个对象属性

# For ex, GET users/lookup API call returns resultset
users = api.lookup_users(screen_names=['StackOverflow,StackExchange'])
# get the length of user and @alecxe mentions
for i in range(len(users)):
    print 'Name - ' + users[i].name
    print 'Bio - ' + users[i].description
    print 'Location - ' + users[i].location
    print 'Joined at - ' + str(users[i].created_at)
    print 'User ID - ' + users[i].id_str
    print ''

<强>输出:

Name - TechCrunch
Bio - Breaking technology news, analysis, and opinions from TechCrunch. Home to Disrupt, TC Sessions, and Startup Battlefield. Got a tip? tips@techcrunch.com
Location - San Francisco, CA
Joined at - 2007-03-07 01:27:09
User ID - 816653

Name - Piwik Analytics
Bio - Piwik is the leading open analytics platform (Web+Mobile). An open alternative to Google Analytics. Privacy is built-in. Tweet about Piwik if you love it!
Location - Planet Earth
Joined at - 2009-06-22 23:47:00
User ID - 49813707