【问题标题】:Saving the file output保存文件输出
【发布时间】:2020-05-24 10:49:21
【问题描述】:

我是编码界的新手,我在开源网站上找到了这段代码。 我正在运行一个 twitter API 流媒体,我希望将输出保存在 csv 文件中。有人可以在我的代码中添加几行来保存输出吗?

我已经标记了需要输入代码的地方

# # # 推特串流监听器# # #

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】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2020-12-29
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多