【发布时间】:2018-09-09 14:19:21
【问题描述】:
我在这里关注this link 以获取所有提及某个查询的推文。 现在,代码到目前为止运行良好,我只是想确保我真正理解任何东西,因为我不想使用某些代码,即使我什至不知道它是如何做的。 这是我的相关代码:
def searchMentions (tweetCount, maxTweets, searchQuery, tweetsPerQry, max_id, sinceId) :
while tweetCount < maxTweets:
if (not max_id):
if (not sinceId):
new_tweets = api.search(q=searchQuery, count=tweetsPerQry)
else:
new_tweets = api.search(q=searchQuery, count = tweetsPerQry, since_id = sinceId)
else:
if (not sinceId):
new_tweets = api.search(q=searchQuery, count= tweetsPerQry, max_id=str(max_id -1))
else:
new_tweets = api.search(q=searchQuery, count=tweetsPerQry, max_id=str(max_id -1), since_id=sinceId)
if not new_tweets:
print("No new tweets to show")
break
for tweet in new_tweets :
try :
tweetCount += len(new_tweets)
max_id = new_tweets[-1].id
tweetId = tweet.user.id
username = tweet.user.screen_name
api.update_status(tweet.text)
print(tweet.text)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
pass
max_id 和 sinceId 都设置为 None 因为还没有找到推文,我想。 tweetCount 设置为零。
我理解它的方式是,while 循环在tweetCount < maxTweets 时运行。例如,我不确定为什么会这样,以及为什么我不能使用while True。一开始我以为这可能与 api 调用的速率有关,但这并没有真正的意义。
然后,该函数检查 max_id 和 sinceId。我假设它检查是否已经有一个 max_id,如果 max_id 没有,它会检查sinceId。如果 sinceId 为 none,那么它只会获取 count 参数设置为多少条推文,否则它将下限设置为 sinceId 并获取多少条推文,count 参数设置为从 sinceId 开始。 如果 max_id 不是 none,但如果 sinceId 设置为 none,它将上限设置为 max_id 并获取一定数量的推文,直到并包括该界限。因此,如果您有 id 为 1、2、3、4、5 且 count=3 和 max_id=5 的推文,您将获得 3、4、5 的推文。否则,它将下限设置为 sinceId 并将上限设置为 max_id 并获取“介于两者之间”的推文。 找到的推文保存在 new_tweets 中。
现在,该函数遍历 new_tweets 中的所有推文,并将 tweetCount 设置为该列表的长度。然后将 max_id 设置为new_tweets[-1].id。由于 twitter 指定 max_id 是包容性的,我假设这被设置为最后一条推文之前的下一条推文,所以推文不会重复,但是,我不太确定,我不明白我的函数如何知道什么最后一条推文之前的 id 可能是。
发布一条重复 new_tweets 中的推文所说的任何内容的推文。
所以,总结一下,我的问题是:
- 我可以用
while True代替while tweetCount < maxTweets吗?如果不能,为什么? - 我解释函数的方式是否正确,如果不正确,我哪里出错了?
-
max_id = new_tweets[-1].id究竟做了什么? - 为什么我们不在 for 循环中将 sinceId 设置为新值?由于一开始就将sinceId设置为None,如果我们不更改任何地方的值,似乎没有必要通过sinceId不设置为None的选项。
作为免责声明:我确实阅读了 Twitter explantion 对 max_id、since_id、计数等的解释,但它没有回答我的问题。
【问题讨论】: