2017-04-20 90 views
0

我一直在使用twitter rails API搞乱,并且无法获取tweet的位置。这似乎总是失败,不会返回任何东西。我也尝试做tweet.coordinates,但它似乎并没有工作。Twitter gem获取tweet的位置

tweets = client.user_timeline("gems") 
puts "size : #{tweets.size}" 
tweets.each do |tweet| 
    if(tweet.place) 
     puts tweet.place.attributes 
    end 
end 

我正在使用以下twitter gem。 https://github.com/sferik/twitter

编辑:

tweets = client.search("a", geocode: "40.7128,-74.0059,50mi").take(100) 
tweets.each do |tweet| 
    if tweet.place? 
     puts tweet.place.full_name 
    elsif tweet.geo? 
     puts "geofound" 
    elsif tweet.user.location? 
     puts tweet.user.location 
    end 

所以,我想上面的代码查找具有地理编码的鸣叫,但似乎没有人有一个地方或地理领域,它总是返回tweet.user。位置,但这不是很准确。输出结果只有纽约的许多,但也来自其他城市,所以我不知道在其他城市不存在/离纽约很远的时候,Twitter如何得到这些查询。我错过了另一个位置字段?我还注意到输出的数量不等于推特数组的大小。

https://pastebin.com/eW18Ri2S

下面是一个例子输出

+0

什么是你的输出?它是否正确显示尺寸?您可以在循环体的第一行尝试'puts tweet.inspect'来查看推文是否存在。 – mahemoff

+0

大小为20.我尝试输出文本,他们都很好。 –

+0

推文是否包含地理元数据?并非所有推文都需要 - 需要选择正确的帐户。即使在Twitter的示例输出中,位置为空https://dev.twitter.com/rest/reference/get/statuses/user_timeline – mahemoff

回答

0

由于twitter宝石文档中提到的,你应该用户place?geo?方法。

空对象

在第4版,方法,你会期望返回一个Twitter对象 将返回零,如果该对象失踪。这可能导致 a NoMethodError。为了避免这样的错误,你可能已经推出 检查响应的感实性,例如:

status = client.status(55709764298092545) 
if status.place 
    # Do something with the Twitter::Place object 
elsif status.geo 
    # Do something with the Twitter::Geo object 
end 

在5版本,所有这些 方法会返回一个Twitter::NullObject代替nil。这应该是 可以防止NoMethodError,但如果您的 具有真实性检查,则可能会导致意外行为,因为除了false和nil外,Ruby 中的所有内容都是真实的。对于这些情况,现在有谓语 方法:

status = client.status(55709764298092545) 
if status.place? 
    # Do something with the Twitter::Place object 
elsif status.geo? 
    # Do something with the Twitter::Geo object 
end 
+0

我尝试了你的建议,但我仍然有一些问题。我做了检查,他们似乎都有一些推特ID。 –