简体   繁体   English

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

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

I am working on tweepy library to use twitter streaming API. 我正在使用tweepy库来使用Twitter流API。 I want to save all those tweets in a .txt file or .csv file. 我要将所有这些推文保存为.txt文件或.csv文件。

//part of my code //我的代码的一部分

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

when i write this line of code and run python getData.py (code file name) on terminal, tweets(with hashtags, id, http and some other) would print after 10 mins around. 当我编写此行代码并在终端上运行python getData.py (代码文件名)时,大约10分钟后将打印tweets(带有标签,id,http等)。

but for saving data in .txt file, when i run python getData.py > getData.txt this. 但是为了将数据保存在.txt文件中,当我运行python getData.py> getData.txt时 It took hours but didn't get any results. 花了几个小时,但没有得到任何结果。

I also tried 我也试过

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

but it is giving me error. 但这给了我错误。 Here's a link of all those errors. 这是所有这些错误的链接

same i tried for .csv file but again getting error. 同样,我尝试为.csv文件,但再次出现错误。

here is my full code. 这是我的完整代码。

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'])

I want to store it on .csv file of .txt file. 我想将其存储在.txt文件的.csv文件中。 How should i solve this problem? 我应该如何解决这个问题? Thank you. 谢谢。

Well, you need to encode your tweet first before you save in csv. 好吧,在保存为csv之前,您需要先对推文进行编码。 It works for me 这个对我有用

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