我用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"))
如果
on_status
方法中的新数据包含所需内容,则可能应该调用另一个函数。没有必要在on_status
方法内部执行continue,因为它不是for循环,除非您创建自己的for循环并根据自己的自定义业务逻辑决定继续。在在幕后,Tweepy库从您的自定义
StreamListener
调用一个名为on_data的继承(StreamListener
)方法。你唯一要负责的就是用这些数据做些什么。在与使用return(它将完全退出函数)不同,您只想继续for循环的下一次迭代而不打印。不过,为了让这有意义,if语句应该在for循环中。在
将
return
替换为continue
,它应该工作得很好。continue
跳过for循环的其余部分,从下一个值开始。在如果希望在for循环之前打印出一个空行,那么将
return
替换为print()
,这样就可以了。在相关问题 更多 >
编程相关推荐