使用 Tweepy 从 Twitter 获取数据并存储在 csv 文件中 [英] Get data from Twitter using Tweepy and store in csv file

查看:45
本文介绍了使用 Tweepy 从 Twitter 获取数据并存储在 csv 文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python、Twitter 和 Tweepy 的新手.我设法从 Twitter 提取数据,但我现在想将其存储到 CSV 文件中.

I'm new to Python, Twitter, and Tweepy. 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 文件.我尝试了几个不同的选项,但它只输出了第一条推文,而不是所有推文.

This prints data out on CLI, but I want it to output to a CSV file. I tried a few different options, but it only outputted the first tweet and not all tweets.

推荐答案

这可以解决问题!

我建议您使用 Python 中的 csv.打开一个文件并在循环中写入它,如下所示:

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 to
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆