Twitter4Jでtwitterのキーワード検索データを収集する
目的
Twitterでコーパスを収集する。ここでは、キーワードでtweetを検索し、その結果をファイルに保存する。
手法
Twitter APIのJavaラッパーであるTwitter4Jを用いる。OAuth認証を使ってアクセスする。
- http://twitter4j.org/ja/index.html
- http://www.atmarkit.co.jp/fsmart/articles/keitaiweb02/01.html
- http://facebook.boo.jp/twitter-api11-limit
exampleを参考にして、以下のようなコードで収集できる。クエリが5秒に1回に制限されているため、sleepで時間を調整している。
/** * @author Masaaki TAKADA * @since Twitter4J 2.1.7 */ public class TweetCollector { /** * Usage: java TweetCollector [path] [query...] * * @param args */ final static int QUERY_NUMBER = 100; final static int SLEEP_TIME = 6000; public static void main(String[] args) { if (args.length < 2) { System.out.println("java TweetCollector [path] [query...]"); System.exit(-1); } for (int i = 1; i < args.length; i++) { try { File file = new File((args[0] + "/" + args[i])); PrintWriter pw = new PrintWriter(new BufferedWriter( new FileWriter(file))); Twitter twitter = new TwitterFactory().getInstance(); Query query = new Query(args[i]); QueryResult result; for (int line = 0; line < QUERY_NUMBER; line++) { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println(tweet.getText()); pw.println(tweet.getText()); } if ((query = result.nextQuery()) == null) { break; } Thread.sleep(SLEEP_TIME); } pw.close(); } catch (TwitterException e) { e.printStackTrace(); System.out.println("Failed to search tweets: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); System.out.println("Failed to open filewriter:" + e.getMessage()); } catch (InterruptedException e) { e.printStackTrace(); System.out.println("Failed in thread sleep:" + e.getMessage()); } } } }