使用Tweepy获取位置

0 投票
1 回答
12093 浏览
提问于 2025-04-18 16:42

我正在尝试找出如何仅在Twitter用户显示位置信息时输出他们的位置。我该怎么做呢?现在我有这个:

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

ckey = ''
csecret = ''
atoken = ''
asecret = ''

class listener(StreamListener):

    def on_status(self, status):
        print status.text
        if status.coordinates:
            print 'coords:', status.coordinates
        if status.place:
            print 'place:', status.place.full_name

        return True

    on_event = on_status

    def on_error(self, status):
        print status
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["twerk"])

补充:最后一行代码出现了错误。我该如何过滤掉“twerk”或“miley”这个词呢?

目前,如果推文中包含“twerk”或“miley”这两个词,就会输出这条推文,但我想要的是只有在推文显示了位置信息的情况下,才能获取这条推文的坐标。我原以为可以用tweet = data.coordinates来实现,但这样并不奏效。有什么好主意吗?

1 个回答

2

当你可以直接把JSON加载为Python对象时,就不要用字符串处理了,可以使用json.loads()

import json
from HTMLParser import HTMLParser


def on_data(self, data):
    data = json.loads(HTMLParser().unescape(data))
    tweet = data['text']
    print tweet
    return True

这样你还可以访问Tweet对象的其他字段,比如坐标:

if data['coordinates']:
    print data['coordinates']

或者地点对象:

if data.get('place'):
    print data['place']['full_name']

对于流式API,你可能想重写on_data()方法,而是使用on_event()on_status()处理器;默认的on_data()实现会加载JSON,并把解析后的Tweepy对象传递给这些处理器:

class listener(StreamListener):

    def on_status(self, status):
        print status.text
        if status.coordinates:
            print 'coords:', status.coordinates
        if status.place:
            print 'place:', status.place.full_name

        return True

    on_event = on_status

    def on_error(self, status):
        print status

我看到这样的消息:

Ainda sonho com uma apresentação de twerk ao vivo  #8BieberManiaNaZonaLivreFM #MTVHottest Justin Bieber
coords: {u'type': u'Point', u'coordinates': [-49.319543, -16.679431]}
place: Goiânia, Goiás

用上面的监听器飞过。

撰写回答