我目前正在编写一个代码来流式处理twitter帖子,并将它们保存到json文件中。同时,textblob决定了tweet的情绪。到目前为止,一切都正常,但没有将所有输出保存到一个文件中。它当前保存tweet,但不保存由textblob计算的情绪得分。这是我用Python编程的第一天,我非常感谢大家的帮助:)
import textblob as textblob
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
from textblob import TextBlob
# consumer key, consumer secret, access token, access secret.
consumer_key = x
consumer_secret = x
access_token = x
access_token_secret = x
class StdOutlistener(StreamListener):
def on_data(self, data):
all_data = json.loads(data)
tweet = TextBlob(all_data["text"])
print(tweet)
print(tweet.sentiment)
# Open json text file to save the tweets
With open('tweets.json', 'a') as tf:
tf.write(data)
return True
def on_error(self, status):
print(status)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitterStream = Stream(auth, StdOutlistener())
twitterStream.filter(languages=["en"], track=["Test"])发布于 2017-08-29 22:27:14
首先,您确定要使用on_data而不是on_status,this详细介绍了两者之间的区别。我对tweepy不太熟悉,所以在这一点上可能是错的。
其次,你似乎没有正确地更新关于情绪的数据。您可以使用tweet = TextBlob(all_data['text'])计算它,但是不需要对tweet变量或all_data变量做任何进一步的处理。你想要的应该是像all_data['sentiment'] = tweet.sentiment这样的东西。
最后,您最终没有正确地将数据写入您的文件。我的假设是,您希望文件是JSON条目的集合,而不是单个JSON文档。您所做的是将提供的字符串data写到文件的末尾,没有新的行,而不是您可能拥有的任何更新的字典。相反,您可能希望将all_data字典作为JSON对象写入文件。
上面几点的修复示例如下:
import textblob as textblob
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
from textblob import TextBlob
# consumer key, consumer secret, access token, access secret.
consumer_key = x
consumer_secret = x
access_token = x
access_token_secret = x
class StdOutlistener(StreamListener):
def on_data(self, data):
all_data = json.loads(data)
tweet = TextBlob(all_data["text"])
#Add the 'sentiment data to all_data
all_data['sentiment'] = tweet.sentiment
print(tweet)
print(tweet.sentiment)
# Open json text file to save the tweets
With open('tweets.json', 'a') as tf:
# Write a new line
tf.write('\n')
# Write the json data directly to the file
json.dump(all_data, tf)
# Alternatively: tf.write(json.dumps(all_data))
return True
def on_error(self, status):
print(status)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitterStream = Stream(auth, StdOutlistener())
twitterStream.filter(languages=["en"], track=["Test"])https://stackoverflow.com/questions/45940984
复制相似问题