Python 使用 Tweepy 从 Twitter 获取数据并存储在 csv 文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21865413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:46:06  来源:igfitidea点击:

Get data from Twitter using Tweepy and store in csv file

pythonpython-2.7csvtwittertweepy

提问by user3325317

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.

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

My code is:

我的代码是:

#!/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

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.

这会在 CLI 上打印数据,但我希望它输出到 CSV 文件。我尝试了几个不同的选项,但它只输出第一条推文而不是所有推文。

采纳答案by Royendgel Silberie

This will do the job!

这将完成工作!

I will recommend you to use csvfrom Python. Open a file and write to it during your loop like this:

我会推荐你​​使用Python 中的csv。打开一个文件并在循环过程中写入它,如下所示:

#!/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()

回答by Asaolu Elijah

You can actually run the program and print the output on another file. Goto CMD and type
python file.py > newFile.py
The output from file.py will be read to newFile.py

您实际上可以运行该程序并在另一个文件上打印输出。转到 CMD 并键入
python file.py > newFile.py
file.py 的输出将被读取到 newFile.py