2017-04-26 55 views
1

我正在嘗試運行一個簡單的腳本,它將傳送實時推文。多次嘗試過濾出轉發失敗。我仍然在我的流中獲得手動轉發(文本「RT @」)。 我試過其他方法,包括linklink忽略轉推Twitter推文時的轉推

由於我學習,我的代碼是非常類似於以下內容:link

我能做些什麼,以忽略銳推?

這裏是我的代碼片段:

class StreamListener(tweepy.StreamListener): 

    def on_status(self, status): 
     if (status.retweeted) and ('RT @' not in status.text): 
      return 

    description = status.user.description 
    loc = status.user.location 
    text = status.text 
    coords = status.coordinates 
    geo = status.geo 
    name = status.user.screen_name 
    user_created = status.user.created_at 
    followers = status.user.followers_count 
    id_str = status.id_str 
    created = status.created_at 
    retweets = status.retweet_count 
    bg_color = status.user.profile_background_color 

    # Initialize TextBlob class on text of each tweet 
    # To get sentiment score from each class 
    blob = TextBlob(text) 
    sent = blob.sentiment 
+0

'status'對象是什麼樣的? – ninesalt

+1

你的邏輯似乎有點困惑 - '(status.retweeted)和('RT @'不在status.text中)'只會返回「官方」轉推。也許你應該使用'(status.retweeted)或('RT @'status.text)'排除「官方」和「手動」轉發 – asongtoruin

回答

0

你可以做的是創造另一個函數在StreamListeneron_status內調用。這是一種適合我的工作:

def analyze_status(text): 
    if 'RT' in text[0:3]: 
     print("This status was retweeted!") 
     print(text) 
    else: 
     print("This status was not retweeted!") 
     print(text) 

class MyStreamListener(tweepy.StreamListener): 
    def on_status(self, status): 
     analyze_status(status.text) 
    def on_error(self, status_code): 
     print(status_code) 

myStreamListener = MyStreamListener() 
myStream = tweepy.Stream(auth=twitter_api.auth, listener=myStreamListener) 
myStream.filter(track=['Trump']) 

這將產生以下:

This status was not retweeted! 
@baseballcrank @seanmdav But they won't, cause Trump's name is on it. I can already hear their stupidity, "I hate D… 
This status was retweeted! 
RT @OvenThelllegals: I'm about to end the Trump administration with a single tweet 
This status was retweeted! 
RT @kylegriffin1: FLASHBACK: April 2016 

SAVANNAH GUTHRIE: "Do you believe in raising taxes on the wealthy?" 

TRUMP: "I do. I do. Inc… 

這還不是最完美的解決方案,但我相信它解決你所面對的問題。

+0

這不會假設「官方」轉推(我相信不必須以「RT @」開始)不被轉推? – asongtoruin

+0

我讓'StreamListener()'長時間運行一個流行的話題,只有在'status.retweeted'打印時纔會打印。 .retweeted屬性可能無法按預期工作? – Brian

+0

嗯,這似乎不尋常。您可以嘗試'hasattr(status,'retweeted_status')',這似乎被傳統的「轉推」和「引用」相當一致地使用,假設它是通過twitter界面完成的。 – asongtoruin