0
作爲Python的新用戶,我遇到了以下代碼的問題。我不需要在屏幕上打印Twitter搜索的結果,而需要保存文件(理想情況下是管道分隔符,我還不知道如何生成...)。但是,下面的代碼運行正常,但不會創建Output.txt文件。它做了一次,然後再也沒有。我在Mac OS上運行它,並用Ctrl + C結束代碼(因爲我仍然不知道如何修改它以返回特定數量的推文)。我認爲這個問題可能與Flush'ing而是力圖包括來自這篇文章的選項後:Flushing issues他們都不似乎工作(除非我做錯了什麼事比可能更多...)保存輸出的Python問題
import tweepy
import json
import sys
# Authentication details. To obtain these visit dev.twitter.com
consumer_key = 'xxxxxx'
consumer_secret = 'xxxxx'
access_token = 'xxxxx-xxxx'
access_token_secret = 'xxxxxxxx'
# This is the listener, resposible for receiving data
class StdOutListener(tweepy.StreamListener):
def on_data(self, data):
# Twitter returns data in JSON format - we need to decode it first
decoded = json.loads(data)
# Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
print '@%s: %s' % (decoded['user']['screen_name'], decoded['text'].encode('ascii', 'ignore'))
print ''
return True
def on_error(self, status):
print status
if __name__ == '__main__':
l = StdOutListener()
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
print "Showing all new tweets for #Microsoft"
stream = tweepy.Stream(auth, l)
stream.filter(track=['Microsoft'])
sys.stdout = open('Output.txt', 'w')
謝謝,這很有道理。恐怕我的編碼水平非常有限,以至於更復雜的建議可能會讓我花費太長時間:/ 但無論如何,這會帶回我原來的問題 - 這個工作有一次,然後看起來Output.txt只是獲取修正;即使我更改名稱並重新運行腳本(我用Ctrl + C關閉它,但我不確定它是否正確)。所以萬一我想運行這個腳本爲不同的關鍵字和寫入不同的文件它不工作... – Zegro 2014-10-31 14:37:27