2014-10-31 31 views
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') 

回答

2

我認爲你會更好地關閉StdOutListener,並讓它直接寫入文件。將sys.stdout分配給一個文件是很奇怪的。這樣,你可以用print的東西進行調試輸出。另請注意,文件模式「w」會在打開文件時截斷文件。

class TweepyFileListener(tweepy.StreamListener): 
    def on_data(self, data): 
     print "on_data called" 
     # Twitter returns data in JSON format - we need to decode it first 
     decoded = json.loads(data) 
     msg = '@%s: %s\n' % (
      decoded['user']['screen_name'], 
      decoded['text'].encode('ascii', 'ignore')) 

     #you should really open the file in __init__ 
     #You should also use a RotatingFileHandler or this guy will get massive 
     with open("Output.txt", "a") as tweet_log: 
      print "Received: %s\n" % msg 
      tweet_log.write(msg) 
+0

謝謝,這很有道理。恐怕我的編碼水平非常有限,以至於更復雜的建議可能會讓我花費太長時間:/ 但無論如何,這會帶回我原來的問題 - 這個工作有一次,然後看起來Output.txt只是獲取修正;即使我更改名稱並重新運行腳本(我用Ctrl + C關閉它,但我不確定它是否正確)。所以萬一我想運行這個腳本爲不同的關鍵字和寫入不同的文件它不工作... – Zegro 2014-10-31 14:37:27