如何在 tweepy 中返回实际的推文?

13

我正在使用 tweepy 编写一个 Twitter 程序。当我运行这段代码时,它会打印 Python 中的一些值,例如

<tweepy.models.Status object at 0x95ff8cc>

这不太好。我该如何获取实际的推文?

import tweepy, tweepy.api
key = XXXXX
sec = XXXXX

tok  = XXXXX
tsec = XXXXX

auth = tweepy.OAuthHandler(key, sec)
auth.set_access_token(tok, tsec)
api = tweepy.API(auth)

pub = api.home_timeline()
for i in pub:
        print str(i)

谢谢。这对于一般对象非常有用。 - earthmeLon
5个回答

24

通常情况下,您可以使用Python中的dir()内置函数来检查一个对象。

似乎Tweepy文档在这里非常缺乏,但我想Status对象应该反映了Twitter的REST状态格式结构,例如,请参见https://dev.twitter.com/docs/api/1/get/statuses/home_timeline

所以,请尝试:

print dir(status)

查看状态对象中的内容

或者简单地说,

print status.text
print status.user.screen_name

1
dir() 是一个很棒的函数。 - tekknolagi

3

看一下getstate()方法,它可以用于检查返回的对象

for i in pub:
    print i.__getstate__()

1
api.home_timeline()方法返回一个包含20个 tweepy.models.Status 对象的列表,对应于前20条推文。也就是说,每个推文被视为 Status 类的一个对象。每个 Status 对象都有许多属性,如 id、text、user、place、created_at 等等。

以下代码将打印推文的 ID 和文本:

tweets = api.home_timeline()
for tweet in tweets:
  print tweet.id, " : ", tweet.text

1

从实际推文中,如果你想要特定的推文,你必须拥有推文ID,并使用该ID。

tweets = self.api.statuses_lookup(tweetIDs)
for tweet in tweets:
  #tweet obtained
  print(str(tweet['id'])+str(tweet['text']))

如果您想要一般的推文内容,请使用Twitter流API。

class StdOutListener(StreamListener):
def __init__(self, outputDatabaseName, collectionName):
    try:
        print("Connecting to database")
        conn=pymongo.MongoClient()
        outputDB = conn[outputDatabaseName]
        self.collection = outputDB[collectionName]
        self.counter = 0
    except pymongo.errors.ConnectionFailure as e:
        print ("Could not connect to MongoDB:")
def on_data(self,data): 
    datajson=json.loads(data)
    if "lang" in datajson and datajson["lang"] == "en" and "text" in datajson:
        self.collection.insert(datajson)

        text=datajson["text"].encode("utf-8") #The text of the tweet
        self.counter += 1
        print(str(self.counter) + " " +str(text))

def on_error(self, status):
    print("ERROR")
    print(status)
def on_connect(self):
    print("You're connected to the streaming server.
l=StdOutListener(dbname,cname)
    auth=OAuthHandler(Auth.consumer_key,Auth.consumer_secret)
    auth.set_access_token(Auth.access_token,Auth.access_token_secret)
    stream=Stream(auth,l)


    stream.filter(track=stopWords)

创建一个从StreamListener继承的Stdoutlistener类,覆盖on_data函数,并以json格式返回tweet。每当获取到tweet时,该函数都会运行。根据停用词过滤tweets,停用词是您想要在tweets中使用的单词列表。

0
在 tweepy 的 Status 实例中,您可以访问 _json 属性,该属性返回一个表示原始 推文内容 的字典。
例如:
type(status)
# tweepy.models.Status

type(status._json)
# dict

status._json.keys()
# dict_keys(['favorite_count', 'contributors', 'id', 'user', ...])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接