Python 返回“None”阻止下一个for循环

2024-04-24 04:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Tweepy来流式推特。我尝试使用json文件中的retweeted_status标识符过滤掉转发的内容。 但我不想在打印出来之前把它打印出来。脚本似乎在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"))

Tags: 文件thetextnameidjsonurlif
2条回答

如果on_status方法中的新数据包含所需内容,则可能应该调用另一个函数。没有必要在on_status方法内部执行continue,因为它不是for循环,除非您创建自己的for循环并根据自己的自定义业务逻辑决定继续。在

在幕后,Tweepy库从您的自定义StreamListener调用一个名为on_data的继承(StreamListener)方法。你唯一要负责的就是用这些数据做些什么。在

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)

与使用return(它将完全退出函数)不同,您只想继续for循环的下一次迭代而不打印。不过,为了让这有意义,if语句应该在for循环中。在

return替换为continue,它应该工作得很好。continue跳过for循环的其余部分,从下一个值开始。在

如果希望在for循环之前打印出一个空行,那么将return替换为print(),这样就可以了。在

相关问题 更多 >