繁体   English   中英

想要使用tweepy将推文数据存储在.txt或.csv文件中

[英]want to store tweets data in .txt or .csv file using tweepy

我正在使用tweepy库来使用Twitter流API。 我要将所有这些推文保存为.txt文件或.csv文件。

//我的代码的一部分

def on_status(self, status):
    print( status.text)

当我编写此行代码并在终端上运行python getData.py (代码文件名)时,大约10分钟后将打印tweets(带有标签,id,http等)。

但是为了将数据保存在.txt文件中,当我运行python getData.py> getData.txt时 花了几个小时,但没有得到任何结果。

我也试过

def on_status(self, status):
    with open("getData.txt","wb") as myFile:
        myFile.write(status)
        myFile.close()

但这给了我错误。 这是所有这些错误的链接

同样,我尝试为.csv文件,但再次出现错误。

这是我的完整代码。

import tweepy
import csv

####input your credentials here
consumer_key = ' '
consumer_secret = ' '
access_token = ' '
access_token_secret = ' '

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

#create a wrapper for the API provided by twitter.
api = tweepy.API( auth )

class TwitterStreamListener(tweepy.StreamListener):
""" A listener handles tweets are the received from the stream.
    This is a basic listener that just prints received tweets to      stdout.
"""

    def on_status(self, status):
        print( status)


# Twitter error list : https://dev.twitter.com/overview/api/response-codes
     def on_error(self, status_code):
         if status_code == 403:
             print("The request is understood, but it has been refused or access is not allowed. Limit is maybe reached")
             return False

#create the stream
streamListener = TwitterStreamListener()

# Add your wrapper and your listner to the stream object
myStream = tweepy.Stream( auth = api.auth, listener = streamListener)

myStream.filter(track=['rajnathsingh'], async=True)
# myStream.filter( follow = ['135421739'])

我想将其存储在.txt文件的.csv文件中。 我应该如何解决这个问题? 谢谢。

好吧,在保存为csv之前,您需要先对推文进行编码。 这个对我有用

status = tweet.text.encode('utf8')
with open('getData.txt', 'a') as myFile:     
                              writer = csv.writer(myFile)
                              writer.writerow([status])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM