我一直在尝试使用tweepy来流媒体推文,然后直接打印它们。我想通过用户和关键字来过滤推文,但似乎并不奏效。当我使用下面的代码时,我得到了所有用户的推文,使用关键字 "hi",当我希望它只从一个特定的用户用户。然而,当我不按关键字过滤时,我得到所有来自特定用户用户的推文。
from __future__ import absolute_import, print_function
from tweepy import OAuthHandler, Stream, StreamListener
# Go to http://apps.twitter.com and create an app.
# The consumer key and secret will be generated for you after
consumer_key = "..."
consumer_secret = "..."
# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
access_token = "..."
access_token_secret = "..."
class StdOutListener(StreamListener):
""" A listener handles tweets that are received from the stream.
This is a basic listener that just prints received tweets to stdout.
"""
def on_data(self, data):
print(data)
return True
def on_error(self, status):
print(status)
if __name__ == '__main__':
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
stream.filter(track=['hi'], follow=["userID"])
试试这个东西。它可能会帮助你。
import re
import tweepy
from tweepy import OAuthHandler
class TwitterClient(object):
# Class constructor or initialization method
def __init__(self):
# keys and tokens from the Twitter Dev Console
consumer_key = ' '
consumer_secret = ' '
access_token = ' '
access_token_secret = ' '
# attempt authentication
try:
# create OAuthHandler object
self.auth = OAuthHandler(consumer_key, consumer_secret)
# set access token and secret
self.auth.set_access_token(access_token, access_token_secret)
# create tweepy API object to fetch tweets
self.api = tweepy.API(self.auth)
except:
print("Error: Authentication Failed")
# Main function to fetch tweets and parse them.
def get_tweets(self, query, languages=["en"], count=10):
# empty list to store parsed tweets
tweets = []
try:
# call twitter api to fetch tweets
fetched_tweets = self.api.search(q=query, count=count)
# parsing tweets one by one
for tweet in fetched_tweets:
# empty dictionary to store required params of a tweet
parsed_tweet = {}
# saving text of tweet
parsed_tweet['text'] = tweet.text
# saving sentiment of tweet
parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)
# appending parsed tweet to tweets list
if tweet.retweet_count > 0:
# if tweet has retweets, ensure that it is appended only once
if parsed_tweet not in tweets:
tweets.append(parsed_tweet)
else:
tweets.append(parsed_tweet)
# return parsed tweets
return tweets
except tweepy.TweepError as e:
# print error (if any)
print("Error : " + str(e))
def main():
searchTerm = input("Type keyword you need to analyze : ")
# creating object of TwitterClient Class
api = TwitterClient()
# calling function to get tweets
#tweets = api.get_tweets(query=searchTerm, count=200)
tweets = tweepy.Cursor(api.search, q=searchTerm, lang="English")
main()