保存文件输出

问题描述 投票:0回答:1

我是编码领域的新手,我在开源上找到了此代码。我正在运行Twitter API流媒体,并且希望将输出保存在csv文件中。有人可以在此处向我的代码添加几行以保存输出吗?

我已经标记了需要输入密码的必要位置

###TWITTER STREAM LISTENER###

class TwitterListener(StreamListener):
    """
    This is a basic listener that just prints received tweets to stdout.
    """
    def __init__(self, fetched_tweets_filename):
        self.fetched_tweets_filename = fetched_tweets_filename

def on_data(self, data):
    try:
        print(data)                                                 **# I wish to save this output**
        with open(self.fetched_tweets_filename, 'a') as tf:
            tf.write(data)
        return True
    except BaseException as e:
        print("Error on_data %s" % str(e))
    return True

def on_error(self, status):
    if status == 420:
        # Returning False on_data method in case rate limit occurs.
        return False
    print(status)                                                  **# I wish to save this output**


class TweetAnalyzer():
    """
    Functionality for analyzing and categorizing content from tweets.
    """
    def tweets_to_data_frame(self, tweets):
        df = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets'])

    df['id'] = np.array([tweet.id for tweet in tweets])
    df['len'] = np.array([len(tweet.text) for tweet in tweets])
    df['date'] = np.array([tweet.created_at for tweet in tweets])
    df['source'] = np.array([tweet.source for tweet in tweets])
    df['likes'] = np.array([tweet.favorite_count for tweet in tweets])
    df['retweets'] = np.array([tweet.retweet_count for tweet in tweets])

    return df



if __name__ == '__main__':

    twitter_client = TwitterClient()
    tweet_analyzer = TweetAnalyzer()

    api = twitter_client.get_twitter_client_api()

    tweets = api.user_timeline(screen_name="Olympics", count=20)

    #print(dir(tweets[0]))
    #print(tweets[0].retweet_count)

    df = tweet_analyzer.tweets_to_data_frame(tweets)
    print(df.head(10))                                             **# I wish to save this output**
python twitter sentiment-analysis
1个回答
0
投票

df.to_csv("PATH/file.csv")应该可以解决问题

© www.soinside.com 2019 - 2024. All rights reserved.