I need to get a filtered sample of twitter stream
I’m using tweepy
I checked the functions for the class Stream to get sample stream and to filter
but I dint’ catch how should I set the class
should it be
stream.filter(track=['']).sample()
stream.sample().filter(track=[''])
or each one in a line or what
And if you have another idea how to get a sample stream based on keyword filters please help
Thanks in advance
3
Answers
I’d suggest reading the api documentation for tweepy. Here you can see how to filter the stream like you want to.
From reading other code snippets, i belive it should be done like this:
As I understand,
tweepy
uses twitter v1.1 APIs, which has separate APIs for sampling and filtering tweets in real time.Twitter API references.
v1 sample-realtime
v1 filter-realtime
Approach 1: one can get filtered stream data using
stream.filter(track=['Keyword1', 'keyord2'])
etc. and then sample records from the collected data.see examples like https://www.storybench.org/how-to-collect-tweets-from-the-twitter-streaming-api-using-python/ Ignoring Retweets When Streaming Twitter Tweets
Approach 2: one can write program that starts and stops streaming in random time intervals (for example, random sampling of 3 min interval in every 15 minutes).
Approach 3: one can instead use the sampling API to collect data and then filter with keyword to store relevant data.
Twitter v2 APIs include an endpoint for random sampling and endpoint for filtered tweets.
The latter allows for specifying a random sample percentage in a query (for example, sample:10 will return a random 10% sample).
Note that v2 APIs are still new and at the moment have a cap of 500k tweets per month.
As an example for the latter, the following code (modified version of this, see this doc) will collect streaming data with cat or dog tags and store it in a json file for every 100 tweets. (Note: this does not include the random sampling query.)
Then, load data in pandas dataframe as
df = pd.read_json('tw_example.json', orient='records')
.