编写Ruby脚本来对Twitter用户的数据进行深度挖掘

2019-09-25 09:39:43王振洲

并非所有的用户或是tweet消息都启用了地理位置功能(出于隐私原因),但这一信息是所有Twitter体验当中的一个非常吸引人的方面。让我们来看一个脚本,该脚本允许你可视化地理定位数据,还有另一个脚本允许你使用这一数据来进行搜索。

第一个脚本(清单12所示)抓取用户的经度和纬度数据(回想一下清单2中的边界框(bounding box)),尽管边界框是一个定义代表了用户区域的多边形,但我做了简化,只用了这一区域中的一个点。有了这一数据,我在一个简单的HMTL文件中生成了一个简单的JavaScript函数,这一JavaScript代码与Google Maps接口,给出了这一位置的一个俯视地图(给出提取自Twitter用户的经度和纬度数据)。

清单12. 构造用户地图的Ruby脚本(where-am-i.rb)

#!/usr/bin/env ruby 
require "rubygems" 
require "twitter" 
 
Twitter.configure do |config| 
config.consumer_key = '<consumer_key> 
config.consumer_secret = '<consumer_secret> 
config.oauth_token = '<oauth_token> 
config.oauth_token_secret = '<token_secret> 
end 
 
screen_name = String.new ARGV[0] 
 
a_user = Twitter.user(screen_name) 
 
if a_user.geo_enabled == true 
 
long = a_user.status.place.bounding_box.coordinates[0][0][0]; 
lat = a_user.status.place.bounding_box.coordinates[0][0][1]; 
 
my_file = File.new("test.html", "w") 
 
my_file.puts "<!DOCTYPE html> 
my_file.puts "<html>< head> 
my_file.puts "<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>" 
my_file.puts "<style type="text/css">" 
my_file.puts "html { height: 100% }" 
my_file.puts "body { height: 100%; margin: 0px; padding: 0px }" 
my_file.puts "#map_canvas { height: 100% }" 
my_file.puts "</style>" 
my_file.puts "< script type="text/javascript"" 
my_file.puts "src="http://maps.google.com/maps/api/js?sensor=false">" 
my_file.puts "</script>" 
my_file.puts "<script type="text/javascript">" 
my_file.puts "function initialize() {" 
my_file.puts "var latlng = new google.maps.LatLng(" + lat.to_s + ", " + long.to_s + ");" 
my_file.puts "var myOptions = {" 
my_file.puts "zoom: 12," 
my_file.puts "center: latlng," 
my_file.puts "mapTypeId: google.maps.MapTypeId.HYBRID" 
my_file.puts "};" 
my_file.puts "var map = new google.maps.Map(document.getElementById("map_canvas")," 
my_file.puts "myOptions);" 
my_file.puts "}" 
my_file.puts "</script>" 
my_file.puts "</head>" 
my_file.puts "<body onload="initialize()">" 
my_file.puts "<div id="map_canvas" style="width:100%; height:100%"></div>" 
my_file.puts "</body>" 
my_file.puts "</html>" 
 
else 
 
puts "no geolocation data available." 
 
end 

清单12中的脚本执行起来很简单:

$ ./where-am-i.rb MTimJones 

最终得出的HTML文件可以通过浏览器来渲染,像这样:

$ firefox test.html