尝试获取tweepy以获取帐户发布的所有推文以写入CSV文件。
程序下载推文但不会将其写入CSV文件
如何才能将推文写入CSV文件
d1 = datetime.date(2016, 8, 4)
for tweet in alltweets:
#if (datetime.datetime.now() - tweet.created_at).days < 1:
#for single_date in daterange(d1, d2):
while True:
if (tweet.created_at == d1):
# transform the tweepy tweets into a 2D array that will populate the csv
#outtweets.append([tweet.user.name, tweet.created_at, tweet.text.encode('UTF-8')])
outtweets.append(list(itertools.chain([tweet.user.name, tweet.created_at],tweet.text.split(' '))))
else:
deadend = True
return
if not deadend:
page += 1
break
#todaysDate = datetime.datetime.now().date()
# write the csv
with open('%s_%s.csv' % (screen_name, d1), 'w', encoding='UTF-8') as f:
writer = csv.writer(f)
writer.writerow(["Username", "Tweeted at", "Text"])
writer.writerows(outtweets)
pass
print ("CSV written")
**编辑1 **
todaysDate = date(2016,8,4)
类侦听器(tweepy.StreamListener):
def on_data(self,data):
print (data)
with open('%s_.csv' % (todaysDate), 'w', encoding='UTF-8') as f:
writer = csv.writer(f)
writer.writerow(["Username", "Tweeted at", "Text"])
writer.writerows(data)
pass
print("CSV Written")
#with open('tweets_file.txt','a') as tf:
#tf.write(data)
#tf.close()
return True
def on_error(self, status):
print (status)
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(access_token, access_secret)
twitterStream=tweepy.streaming.Stream(auth, listener())
while (todaysDate == date(2016, 8, 4)):
twitterStream.filter()
todaysDate = date.now()
print("CSV Written")
答案 0 :(得分:0)
尝试以下操作(在此示例中,使用“Barry”一词获取推文):
from tweepy.streaming import Stream
from tweepy import OAuthHandler
from tweepy import StreamListener
ckey='yourCkey'
csecret='yourCsecret'
atoken='yourAtoken'
asecret='yourAsecret'
class listener(StreamListener):
def on_data(self,data):
print data
with open('tweets_file.txt','a') as tf:
tf.write(data)
tf.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=['Barry'])