使用Tweepy从Twitter获取数据,并存储在csv文件中 [英] Get data from Twitter using Tweepy and store in csv file
本文介绍了使用Tweepy从Twitter获取数据,并存储在csv文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是python / twitter / tweepy的新手,我设法从Twitter中提取数据,但我现在要把它存储到csv文件中
I'm new to python/twitter/tweepy and I managed to pull data from Twitter but I now want to store it into a csv file
我的代码是:
#!/usr/bin/python
import tweepy
auth = tweepy.auth.OAuthHandler('XXXXXX', 'XXXXXXX'
auth.set_access_token('XXX-XXX', 'XXX'
api = tweepy.API(auth)
for tweet in tweepy.Cursor(api.search,
q="google",
since="2014-02-14",
until="2014-02-15",
lang="en").items():
print tweet.created_at, tweet.text
这打印数据输出在CLI,但我想要输出到一个csv,我尝试了几个不同的选项,但它只输出第一个tweet,而不是所有的tweets
This prints data out on CLI but I want it to output to a csv, I tried a few different options but it only outputted the first tweet and not all tweets
任何帮助都会感激。
推荐答案
请使用Python中的 csv 。
打开一个文件,在循环过程中这样写:
This will do the job! I will recommend you to use csv from Python. Open a file and write to it during your loop like this :
#!/usr/bin/python
import tweepy
import csv #Import csv
auth = tweepy.auth.OAuthHandler('XXXXXX', 'XXXXXXX')
auth.set_access_token('XXX-XXX', 'XXX')
api = tweepy.API(auth)
# Open/Create a file to append data
csvFile = open('result.csv', 'a')
#Use csv Writer
csvWriter = csv.writer(csvFile)
for tweet in tweepy.Cursor(api.search,
q="google",
since="2014-02-14",
until="2014-02-15",
lang="en").items():
#Write a row to the csv file/ I use encode utf-8
csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8')])
print tweet.created_at, tweet.text
csvFile.close()
这篇关于使用Tweepy从Twitter获取数据,并存储在csv文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文