【问题标题】:Alternative to Twitter APITwitter API 的替代方案
【发布时间】:2018-01-28 07:04:57
【问题描述】:

我正在从事一个项目,我从 Twitter API 流式传输推文,然后应用情绪分析并在交互式彩色地图上可视化结果。

我已经在 python 中尝试了 'tweepy' 库,但问题是它只检索很少的推文(10 或更少)。

另外,我将指定语言和位置,这意味着我可能会收到更少的推文!我需要成百上千条推文的实时流。

这是我尝试过的代码(以防万一):

import os
import tweepy
from textblob import TextBlob

port = os.getenv('PORT', '8080')
host = os.getenv('IP', '0.0.0.0')

# Step 1 - Authenticate
consumer_key= 'xx'
consumer_secret= 'xx'

access_token='xx'
access_token_secret='xx'

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

api = tweepy.API(auth)

#Step 3 - Retrieve Tweets
public_tweets = api.search('school')

for tweet in public_tweets:

    print(tweet.text)
    analysis = TextBlob(tweet.text)
    print(analysis)

有没有更好的选择?我找到了“PubNub”,它是一个 JavaScript API,但现在我想要 python 中的东西,因为它对我来说更容易。

谢谢

【问题讨论】:

    标签: python api twitter sentiment-analysis


    【解决方案1】:

    如果你想要大量的推文,我建议你使用 Twitter 的流媒体 API,使用 tweepy

    #Create a stream listner:
    import tweepy
    tweets = []
    class MyStreamListener(tweepy.StreamListener):
    #The next function defines what to do when a tweet is parsed by the streaming API
        def on_status(self, status):
            tweets.append(status.text)
    
    #Create a stream:
    myStreamListener = MyStreamListener()
    myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener)
    
    #Filter streamed tweets by the keyword 'school':
    myStream.filter(track=['school'], languages=['en'])
    

    请注意,此处使用的跟踪过滤器是标准的免费过滤 API,其中还有另一个名为 PowerTrack 的 API,专为有更多过滤要求和规则的企业构建。

    参考:https://developer.twitter.com/en/docs/tweets/filter-realtime/overview/statuses-filter


    否则,如果你想坚持search方法,你可以通过添加count查询最多100条推文,并在解析的最大id上使用since_id来获取新推文,你可以将这些属性添加到search方法如下:

    public_tweets = []
    max_id = 0
    for i in range(10): #This loop will run 10 times you can play around with that
        public_tweets.extend(api.search(q='school', count=100, since_id=max_id))
        max_id = max([tweet.id for tweet in public_tweets])
    
    #To make sure you only got unique tweets, you can do:
    unique_tweets = list({tweet._json['id']:tweet._json for tweet in public_tweets}.values())
    

    这样,您必须小心 API 的限制,并且您必须在初始化 API 时通过启用 wait_on_rate_limit 属性来处理它:api = tweepy.API(auth,wait_on_rate_limit=True)

    【讨论】:

    • 谢谢!但我得到了问题(页面参数无效)
    • 我已经更新了我的答案,因为页面属性在文档中但不在源代码中。它现在应该可以工作了。
    • 如果你想尝试不同的库,这里有一个简化的例子,它调用 Twitter 的搜索请求并处理获取连续的推文页面(直到推文用完)。 github.com/geduldig/TwitterAPI/blob/master/examples/…
    • 我正在尝试测试代码,但我不断收到(预期的缩进块)我试图解决它,但没有任何效果
    • @user8423460 我刚刚下载了代码,它对我有用。唯一需要缩进的地方是 for 循环内的第 21 行。哪一行给了你错误?
    猜你喜欢
    • 2014-02-02
    • 2012-07-07
    • 2011-01-27
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2019-12-10
    • 2011-01-03
    相关资源
    最近更新 更多