簡體   English   中英

Python返回“無”可防止跟隨for循環

[英]Python return “None” prevents following for loop

我正在使用Tweepy流推文。 我正在嘗試使用json文件中的retweeted_status標識符過濾掉轉發的內容。 我希望for循環在它之前的行上的空返回之后執行,但是它似乎不起作用-沒有輸出任何內容。 該腳本似乎在if語句之后停止:

class StreamListener(tweepy.StreamListener):


        def on_status(self, status):
                #these variable split out the data from the outputted json
                text = status.text
                name = status.user.screen_name
                id_str = status.id_str

#This if argument ensures that if there is retweeted status then None is returned
                if hasattr (status, 'retweeted_status'):
                        return
                for url in status.entities['urls']:

                        print (text, name, (url['expanded_url']), file=open("results.txt", "a"))

而不是使用return(將完全退出函數),您只想繼續進行for循環的下一個迭代而無需打印。 盡管這樣做很有意義,但是您的if語句應該在for循環內。

替換returncontinue ,它應該工作的偉大。 continue略過剩下的for循環,並開始對下一個值。

如果您希望在for循環之前打印出空行,請用print()替換return ,而這將會發生。

如果on_status方法中的新數據包含所需的內容,則可能應該調用另一個函數。 無需在on_status方法內進行繼續操作,因為它不是for循環,除非您創建自己的for循環並根據自己的自定義業務邏輯決定繼續。

在幕后,Tweepy庫正在從名為on_data的自定義StreamListener調用InheritedStreamListener )方法。 您唯一要做的就是對數據進行處理或不進行處理。

def handle_status_update(status):
    # Handle your custom stuff in here...
    text = status.text
    name = status.user.screen_name
    id_str = status.id_str

    for url in status.entities['urls']:
        print (text, name, (url['expanded_url']), file=open("results.txt", "a"))


class StreamListener(tweepy.StreamListener):


        def on_status(self, status):
            # if not retweeted
            if not hasattr (status, 'retweeted_status'):
                handle_status_update(status)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM