2017-02-25 81 views
-1

我想獲得下面的代碼,以排除包含列表中的限制詞的任何推文。做這個的最好方式是什麼?Tweepy - 限制某些推文

此代碼還返回只有最後一次我打破流的鳴叫。有沒有辦法將所有適用的推文打印成CSV?

import sys 
import tweepy 
import csv 

#pass security information to variables 
consumer_key = '' 
consumer_secret = '' 
access_key = '' 
access_secret = '' 


#use variables to access twitter 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_key, access_secret) 
api = tweepy.API(auth) 

#create an object called 'customStreamListener' 

class CustomStreamListener(tweepy.StreamListener): 

    def on_status(self, status): 
     print (status.author.screen_name, status.created_at, status.text) 
     # Writing status data 
     with open('OutputStreaming.csv', 'w') as f: 
      writer = csv.writer(f) 
      writer.writerow([status.author.screen_name, status.created_at, status.text]) 


    def on_error(self, status_code): 
     print >> sys.stderr, 'Encountered error with status code:', status_code 
     return True # Don't kill the stream 

    def on_timeout(self): 
     print >> sys.stderr, 'Timeout...' 
     return True # Don't kill the stream 

# Writing csv titles 
with open('OutputStreaming.csv', 'w') as f: 
     writer = csv.writer(f) 
     writer.writerow(['Author', 'Date', 'Text']) 

streamingAPI = tweepy.streaming.Stream(auth, CustomStreamListener()) 
streamingAPI.filter(track=['Hasbro', 'Mattel', 'Lego']) 
+0

你解決這個問題? – Giordano

+0

還在黑客嗎? – JoshGumby87

+0

我覺得我在這裏很好。我得到它運行,但過濾也許我需要進一步研究使用不同的包。 – JoshGumby87

回答

0

Twitter的API中的documentation for the track parameter表明,它是不可能從過濾器排除條款,只包括單詞和短語。您必須在代碼中實施額外的過濾器,以放棄包含您不希望包含在結果集中的單詞的Tweets。

+0

我想這將是我真正的問題。在上面的實際代碼中實現這個最好的方法是什麼? – JoshGumby87

+0

裏面的on_status實現一個檢查,看看status.text並在寫入文件之前提前發生,如果文本包含您不感興趣的文字 –

+0

謝謝我會給這個樣子 – JoshGumby87

0

從過濾器函數中排除條件是不可能的,但您可以實現自定義選擇。 基本上這個想法是檢查推文的單詞是否包含不允許的單詞。 您可以使用nltk模塊簡單標記推文的文本。

從NLTK網頁一個簡單的例子:

>>> import nltk 
>>> sentence = """At eight o'clock on Thursday morning 
... Arthur didn't feel very good.""" 
>>> tokens = nltk.word_tokenize(sentence) 
>>> tokens 
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning', 
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.'] 

東北角,你的情況是sentence tweet.text。 因此改變你的代碼與此類似:

def on_status(self, status): 
    print (status.author.screen_name, status.created_at, status.text) 
    is_allowed = True 
    banned_words = ['word_1', 'word2', 'another_bad_word'] 
    words_text = nltk.word_tokenize(status.text) 

    # loop banned_words and search if item is in words_text 
    for word in banned_words: 
     if word in words_text: 
      # discard this tweet 
      is_allowed = False 
      break 

    if is_allowed is True: 
     # stuff for writing status data 
     # ... 

此代碼尚未經過測試,但顯示你的方式來達到自己的目標。

讓我知道

+0

不熟悉如何使用NLTK有沒有什麼地方比文檔更容易解釋如何使用。 – JoshGumby87