Python+Tweepy(STREAM API)解析特定值/对象的JSON输出

2024-10-01 15:37:14 发布

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

找到了答案:我在朋友的帮助下找到了解决方案。我忘了尝试json.loads()函数——它与print json.loads(data)['text']一起工作。在

问题:

我正试图通过Tweepy试验Twitter的流媒体API。我已经得到了要运行的示例代码,它根据特定的关键字过滤流,并将每个tweet的整个JSON信息块转储到stdout。在

作为JSON和twitter API的新手,我不知道如何将某个属性(比如海报的名称或tweet的实际文本)提取到字符串中。在

我已经确定进入stdout的JSON输出是Unicode对象,我不知道如何访问JSON中的各种元素。在

我使用的是python2.7.9(是否应该升级到3.x?)和Tweepy 3.3.0版。下面的代码是我在google上找到的一个随机流式API教程的基本未经修改的版本。在

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json

consumer_key = "IS A SECWET"
consumer_secret = "IS A SECWET"
access_token = "IS A SECWET"
access_token_secret = "IS A SECWET"


class StdOutListener(StreamListener):

    def on_data(self, data):
        print data # here I would like to print ONLY the tweet's text, not the entire JSON dump.
        return True

    def on_error(self, status):
        print status


if __name__ == '__main__':

    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l)

    stream.filter(track=['#testing'])

以下是终端中一条tweet的输出:

^{pr2}$

Tags: fromimporttokenapijsondatasecretaccess

热门问题