将twitteR包中的userTimeline编写为Twitter中用户列表中的数据,记录列表中缺少的用户

时间:2014-03-07 18:26:33

标签: r twitter

我正在尝试编译特定Twitter用户子集的usertimelines语料库。我的问题是,在现有代码(下面给出)中,当用户的帐户被暂停或删除时,代码中断,提供所提供的输出&错误(下面)

   ## ORIGINAL ##
   for (user in users){

  # Download user's timeline from Twitter
  tweets <- userTimeline(user)

  # Extract tweets
  tweets <- unlist( lapply(tweets, function(t) t$getText() ) )

  # Save tweets to file
  write.csv(tweets, file=paste(user, ".csv", sep=""), row.names=F)
  #Sys.sleep(sleepTime)
}
  

[1]“未找到”   twInterfaceObj $ doAPICall中的错误(cmd,params,method,   ...):错误:未找到

我的问题是,如何让脚本保持运行,为“丢失”(已删除/无效)帐户保存某种空结果?

我在R:ftp://cran.r-project.org/pub/R/web/packages/twitteR/twitteR.pdf

中使用twitteR包
   #EDIT#
# Extract tweets
# Pause for 60 sec
sleepTime = 60

for (user in users) 
{
  # tell the loop to skip a user if their account is protected 
  # or some other error occurs  
  result <- try(userTimeline(user), silent = TRUE);
  if(class(result) == "try-error") next;
  # Download user's timeline from Twitter
  tweets <- userTimeline(user)

  # Extract tweets
  tweets <- unlist( lapply(tweets, function(t) t$getText() ) )

  # Save tweets to file
  write.csv(tweets, file=paste(user, ".csv", sep=""), row.names=F)

  # Tell the loop to pause for 60s between iterations to avoid exceeding the Twitter API request limit
  print('Sleeping for 60 seconds...')
  Sys.sleep(sleepTime); 
}
#
# Now inspect tweets to see the user's timeline data

1 个答案:

答案 0 :(得分:1)

你可以捕获异常。请参阅?try?tryCatch。例如:

 tweets <- try(userTimeline(user),silent=TRUE)
 if(inherits(tweets ,'try-error')) 
   return(NULL)
 else{
    ## process normally here  
 }