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

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

如果没有可用的位置信息的话,这一脚本就会执行失败;不过如果执行成功的话,就会生成一个HTML文件,浏览器可以读入该文件来渲染出地图。图5给出了最终生成的地图图像,其显示了美国科罗拉多州北部Front Range的部分地区。

图5. 清单12中的脚本渲染图像的例子

20151110143516592.jpg (543×428)

有了地理位置,你还可以通过搜Twitter来识别出与某个特定位置相关联的Twitter用户和tweet消息。Twitter搜索API允许使用地理编码信息来限定搜索结果。下面清单13中的例子提取用户的经度和纬度,然后使用这些数据获取该位置方圆5公里之内的所有tweet消息。

清单13. 使用经度和纬度数据来搜索局部地区的tweet消息(tweets-local.rb)

#!/usr/bin/env ruby 
require "rubygems" 
require "twitter" 
 
Twitter.configure do |config| 
config.consumer_key = '' 
config.consumer_secret = '' 
config.oauth_token = '' 
config.oauth_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] 
 
Array tweets = Twitter::Search.new.geocode(lat, long, "5mi").fetch 
 
tweets.each do |t| 
 
puts t.from_user + " | " + t.text 
 
end 
 
end 

清单13中的脚本的执行结果显示在清单14中,这是指定位置范围内的Twitter用户发布的tweet消息的一个子集。

清单14. 查询我所在位置方圆5公里之内的这一局部地区的tweet消息。

$ ./tweets-local.rb MTimJones 
Breesesummer | @DaltonOls did he answer u 
LongmontRadMon | 60 CPM, 0.4872 uSv/h, 0.6368 uSv/h, 2 time(s) over natural radiation 
graelston | on every street there is a memory; a time and place we can never be again. 
Breesesummer | #I'minafight with @DaltonOls to see who will marry @TheCodySimpson I will 
marry him!!! :/ 
_JennieJune_ | ok I'm done, goodnight everyone! 
Breesesummer | @DaltonOls same 
_JennieJune_ | @sylquejr sleep well! 
Breesesummer | @DaltonOls ok let's see what he says 
LongmontRadMon | 90 CPM, 0.7308 uSv/h, 0.7864 uSv/h, 2 time(s) over natural radiation 
Breesesummer | @TheCodySimpson would u marry me or @DaltonOls 
natcapsolutions | RT hlovins: The scientific rebuttal to the silly Forbes release this 
morning: Misdiagnosis of Surface Temperatu... http://bit.ly/nRpLJl 
$ 

继续深入

本文给出了一些简单的脚本,这些脚本使用Ruby语言来从Twitter中提取数据,文章的重点放在用来说明一些基本概念的脚本的开发和演示方面,但我们能做的远不止于此。例如,你还可以使用API来浏览你的朋友的网络,并找出你感兴趣的最受欢迎的Twitter用户。另一个吸引人的方面是对tweet消息本身进行挖掘,使用地理位置数据来了解基于位置的行为或是事件(比如说流感暴发)。本文只是做了一个浅显的介绍,请在下面随意发表你的评论,附上你自己的各种混搭程序。Ruby和Twitter gem把为数据挖掘需要开发有用的混搭应用程序和仪表盘工具的工作变得很容易。