2013-07-23 49 views
0

我有一個用Python編寫的文件,發送到Twitterstream並根據列表中的關鍵字獲取消息。名單很長,輸出不是我想要的。我想清理文件並將結果輸出到文本文件。輸出Tweepy TwitterStreamer到Python 2.7中的.csv

這裏是我當前的代碼,這將所有郵件寫入一行:

import sys 
.... 

if __name__ == '__main__': 
    with open("keywords.txt", "r") as f: 
     keywords = f.readlines() 


    l = StdOutListener()  
    auth = OAuthHandler(consumer_key, consumer_secret)  
    auth.set_access_token(access_token, access_token_secret)  

    stream = Stream(auth, l)   
    stream.filter(track=keywords]) 

以上不拉任何東西,沒什麼意思是輸出到當我輸入一個文本文件,在命令如下提示python hashtagworking.py > output.txt stream.filter有大約300個項目,所以我想用一個txt文件來代替實際的文本。此外,每條消息的結果都顯示在一條消息中,我將其重寫爲輸出到消息中每個對象的csv文件。

我覺得這是我所期待的,但想確保:similar problem

我也想從其他嵌套對象之類的實體:{...}具體我想從實體對象獲取哈希標籤,但更具體地說是任何對象。我嘗試過的東西,如data.text.hashtagdata.entities.hashtagdata.entities.media.hashtag都無濟於事。

回答

1

對於關鍵字的問題,假設你已經把他們都在一個txt文件(每行一個標記)

with open("tokens.txt", "r") as f: 
    tokens = f.readlines() 

.... 
stream.filter(track=tokens) 

您的其他問題,你可以寫下來的例子(以.csv輸出)你想在文件中想要什麼?

class StdOutListener(StreamListener):   
     """ A listener handles tweets are the received from the stream. 
     This is a basic listener that just prints received tweets to stdout. 

     """   
    def on_status(self, data):    
     try:     
      print '%s , %s , %s , %s' % (data.text,\ <-- change to data.csv?    
      data.author.screen_name,data.created_at,data.source) 
      with open("data.csv", 'a+') as f: 
       f.write("{text},{name},{created},{source}\n" 
         .format(text=str(data.text), 
           name=str(data.author.screen_name), 
           created=str(data.created_at), 
           source=str(data.source)))    
      return True    
     except Exception, e:     
      print >> sys.stderr, 'Encountered Exception:', e     
      pass   

    def on_error(self, status):    
     return True 

注意,是不是一個可以接受的長期解決方案爲你打開每一個鳴叫從流過濾時關閉文件(又名驅I/O),你可以做的。將實現一個緩衝區(每當緩衝區被填滿時,將其轉儲到文件中)。

請注意,我在CSV文件中手動寫,如果你想在CSV操控更深處請看看http://docs.python.org/2/library/csv.html

+0

謝謝@ketouem爲csv文件,我期待轉儲在代碼中被分隔的任何東西中,如果我有一天有5個元素,然後在第二天添加第6個元素,我希望第6個元素被添加。我將介紹你列出的文檔,我還必須弄清楚如何從「實體」部分中分解出元素,我可能必須定義一個函數,或者學習如何分解json。 –

+0

我將代碼更新爲我正在處理的問題 –

+1

請注意,您可以使用eponym(&builtin)模塊http://docs.python.org/2/library/json輕鬆操作原始json數據。 HTML – Ketouem