[英]Saving the file output
I am new to the coding world and I found this code on open source.我是编码世界的新手,我在开源中找到了这段代码。 I am running a twitter API streamer and I wish to save the outputs in csv file.
我正在运行 twitter API 流媒体,我希望将输出保存在 csv 文件中。 can someone add few lines to my code here to save the output?
有人可以在我的代码中添加几行来保存 output 吗?
I have marked the required places where codes need to be entered我已经标记了需要输入代码的地方
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**
df.to_csv("PATH/file.csv")
should do the trick df.to_csv("PATH/file.csv")
应该可以解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.