首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按位置过滤Tweets

按位置过滤Tweets
EN

Stack Overflow用户
提问于 2015-05-27 23:43:22
回答 1查看 810关注 0票数 0

我试图修改这个脚本,只保存带有一个位置的tweet的JSON,并且在Python中遇到了一个问题,在那里检查不为空似乎不起作用。have键不能正常工作,因为它们都有键,其中大多数都是'null‘。不是没有工作,因为Python认为空和没有不同,并检查它作为文本不为“空”也没有工作。有没有人对如何解决这个问题有一个聪明的主意?

代码语言:javascript
复制
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import pymongo
import tweepy
import json


#Variables that contains the user credentials to access Twitter API 
access_key = '' #redacted for privacy and such
access_secret = ''
consumer_key = ''
consumer_secret = ''

#Runs auth to Twitter API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)


#This is a basic listener that will print incoming data to stdout
class StdOutListener(StreamListener):

    def on_data(self, data):
        print data
        return True

    def on_error(self, status):
        print status


#Customizes the stream and saves text and lang to databases 
class CustomStreamListener(tweepy.StreamListener):
    def __init__(self, api):
        self.api = api
        super(tweepy.StreamListener, self).__init__()
        self.db = pymongo.MongoClient('localhost', 27017).crime



    def on_data(self, data):
        jd = json.loads(data)
        if jd.has_key('coordinates') :
            self.db.tweets.insert( { 'text' : jd['text'], 'coordinates' : jd['coordinates'], 'lang' : jd['lang'] } )




    def on_error(self, status_code):
        return True # Don't kill the stream

    def on_timeout(self):
        return True # Don't kill the stream

#Calls on StreamListerner and provides specifications of tracking
l = tweepy.streaming.Stream(auth, CustomStreamListener(api))
l.filter(track=['guns'])
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-10 12:22:59

您可以尝试检查字符串的长度:

代码语言:javascript
复制
if len( jd['coordinates'] ) > 1:
    self.db.tweets.insert( { 'text' : jd['text'], 'coordinates' : jd['coordinates'], 'lang' : jd['lang'] } )
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30494954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档