2017-04-20 88 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。 –