如何为tweepy模块添加位置过滤器
我找到了一段代码,这段代码在Python Shell中可以很好地让我查看Twitter的标准1%的数据流:
import sys
import tweepy
consumer_key=""
consumer_secret=""
access_key = ""
access_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
print status.text
def on_error(self, status_code):
print >> sys.stderr, 'Encountered error with status code:', status_code
return True # Don't kill the stream
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True # Don't kill the stream
sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(track=['manchester united'])
我该如何添加一个过滤器,只解析来自特定地点的推文呢?我看到有人在其他与Twitter相关的Python代码中添加了GPS信息,但我在Tweepy模块中找不到与sapi相关的具体内容。
有什么想法吗?
谢谢
4 个回答
sapi.filter(track=['曼联'], locations=['GPS坐标'])
在实时处理的时候,你不能直接过滤这些内容,但如果你把推文写入一个文件的话,可以在输出阶段进行过滤。
胡安给出了正确的答案。我只用这个来过滤德国的数据:
# Bounding boxes for geolocations
# Online-Tool to create boxes (c+p as raw CSV): http://boundingbox.klokantech.com/
GEOBOX_WORLD = [-180,-90,180,90]
GEOBOX_GERMANY = [5.0770049095, 47.2982950435, 15.0403900146, 54.9039819757]
stream.filter(locations=GEOBOX_GERMANY)
这个方法有点粗糙,它包含了一些其他国家的部分区域。如果你想要更精确的结果,可以把多个区域组合起来,以覆盖你需要的位置。
不过需要注意的是,如果你通过地理标签来过滤,推文的数量会大大减少。这是我测试数据库中大约500万条推文的结果(这个查询应该能返回实际包含地理位置的推文百分比):
> db.tweets.find({coordinates:{$ne:null}}).count() / db.tweets.count()
0.016668392651547598
所以在我抽样的1%推文中,只有1.67%包含地理标签。不过还有其他方法可以找出用户的位置:http://arxiv.org/ftp/arxiv/papers/1403/1403.2345.pdf
这个流式API不允许同时按地点和关键词进行过滤。
边界框并不能作为其他过滤条件的过滤器。举个例子,track=twitter&locations=-122.75,36.8,-121.75,37.8 这个设置会匹配任何包含“Twitter”这个词的推文(即使不是地理位置相关的推文)或者来自旧金山地区的推文。
来源:https://dev.twitter.com/docs/streaming-apis/parameters#locations
你可以向流式API请求关键词或特定地点的推文,然后在你的应用中对结果进行过滤,查看每条推文。
如果你按照以下方式修改代码,你将捕获到来自英国的推文,然后再过滤出只包含“manchester united”的推文。
import sys
import tweepy
consumer_key=""
consumer_secret=""
access_key=""
access_secret=""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
if 'manchester united' in status.text.lower():
print status.text
def on_error(self, status_code):
print >> sys.stderr, 'Encountered error with status code:', status_code
return True # Don't kill the stream
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True # Don't kill the stream
sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(locations=[-6.38,49.87,1.77,55.81])