简体   繁体   English

使用 Tweepy 在一次通话中获取不同主题标签的推文

[英]Getting tweets for different hashtags in one call using Tweepy

I want to get popular and recent tweets for different Hash tags, with Tweepy.我想使用 Tweepy 获取不同 Hash 标签的流行和最新推文。 The solution I have right now is shown below.我现在的解决方案如下所示。 But this method does a separate call for each hashtag, which is not good in the presence of rate limitations.但是这种方法对每个主题标签进行单独调用,这在存在速率限制的情况下并不好。 Is it possible to do this in one call?是否有可能在一个电话中做到这一点? If so, how?如果是这样,怎么做?

for ht in hash_tags:
    tweets = tweepy.Cursor(api.search, ht + " -filter:retweets", 
        result_type='mixed', since=date_since, 
        tweet_mode='extended').items(num_of_tweets)
    add_tweets(tweets)

Rather than running a for loop in which you search for one hashtag at a time, you can run a search which contains many of the hashtags you need using the OR operator from Twitter's standard search operators .您可以使用Twitter 标准搜索运算符中的 OR 运算符运行包含您需要的许多主题标签的搜索,而不是运行一次搜索一个主题标签的for循环。 This is a broader search, and you'll get a mixed bag of results for each hashtag, but it cuts down on the number of requests you make overall.这是一个更广泛的搜索,您会得到每个主题标签的混合结果,但它会减少您提出的总体请求数量。

So add all of your hashtags to a string, and pass this through as your query.因此,将所有主题标签添加到字符串中,并将其作为查询传递。

#just an example, not the nicest!
    query_string = ""
    for i in hash_tags:
        if i == hash_tags[-1]:
            query_string+=str(i)
        else:
            query_string+=str(i) + " OR "
    tweets = tweepy.Cursor(api.search, q=query_string + " -filter:retweets", 
    result_type='mixed', since=date_since, 
    tweet_mode='extended').items(num_of_tweets)
add_tweets(tweets)

This means your search will be something like #coolstuff OR #reallycoolstuff OR #evencoolerstuff .这意味着您的搜索将类似于#coolstuff OR #reallycoolstuff OR #evencoolerstuff It may be worth increasing the number of items returned when doing this, as the search will be so much more broad.这样做可能值得增加返回的项目数量,因为搜索范围会更广。

Keep in mind that there are limits to the size of query you can search with, so you may need to break this down into smaller queries if you've got a lot of hashtags.请记住,您可以搜索的查询大小是有限制的,因此如果您有很多主题标签,则可能需要将其分解为较小的查询。 This may also help you get better results (eg a more popular hashtag in your query string taking up a lot of your results, so do a separate search for less popular hashtags separately; how you'd measure that though, would be up to you!)这也可以帮助您获得更好的结果(例如,您的查询字符串中更受欢迎的主题标签会占用您的大量结果,因此请单独搜索不太受欢迎的主题标签;不过,您如何衡量这一点取决于您!)

Hope this helps you get started.希望这可以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM