我目前正在使用python进行一些研究,使用针对特定主题的Twitter数据的情绪分析(对于这个问题不一定重要),其中我是初学者。我了解twitter流API限制用户只能访问前7天,除非您申请完整的企业搜索,这将打开整个存档。我最近从twitter获得了这个研究项目的完整档案,但是我无法指定我想要流入csv文件的推文的开始和结束日期。这是我的代码:
import pandas as pd
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
ckey = 'xxxxxxxxxxxxxxxxxxxxxxx'
csecret = 'xxxxxxxxxxxxxxxxxxxxxxx'
atoken = 'xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxx'
asecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# =============================================================================
# def sentimentAnalysis(text):
# output = '0'
# return output
# =============================================================================
class listener(StreamListener):
def on_data(self, data):
tweet = data.split(',"text":"')[1].split('","source')[0]
saveMe = tweet+'::'+'\n'
output = open('output.csv','a')
output.write(saveMe)
output.close()
return True
def on_error(self, status):
print(status)
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["#weather"], languages = ["en"])
现在,这段代码完美地汇集了过去7天的推特日期。我尝试将底线更改为
twitterStream.filter(track=["#weather"], languages = ["en"], since = ["2016-06-01"])
但这会返回此错误:: filter()得到一个意外的关键字参数'since'。
按给定日期框架过滤的正确方法是什么?
答案 0 :(得分:0)
tweepy不提供“since”参数,因为您可以自己检查here。
要获得所需的输出,您必须使用api.user_timeline
,遍历页面直到达到所需的日期,例如:
import tweepy
import datetime
# The consumer keys can be found on your application's Details
# page located at https://dev.twitter.com/apps (under "OAuth settings")
consumer_key=""
consumer_secret=""
# The access tokens can be found on your applications's Details
# page located at https://dev.twitter.com/apps (located
# under "Your access token")
access_token=""
access_token_secret=""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
page = 1
stop_loop = False
while not stop_loop:
tweets = api.user_timeline(username, page=page)
if not tweets:
break
for tweet in tweets:
if datetime.date(YEAR, MONTH, DAY) < tweet.created_at:
stop_loop = True
break
# Do the tweet process here
page+=1
time.sleep(500)
请注意,您需要更新代码以满足您的需求,这只是一般解决方案。