我目前正在创建应根据关键字搜索推文的代码。我最初使用twitter4j API创建了一个流光,但却发现你无法过滤多个过滤器。我的代码列在下面。
public class TweetStreamer {
public static void stream(String[] apiKeys, String[] stopwords, long[] users, double[][] coordinates, BiConsumer<Status, String> fn) throws InterruptedException {
// Save the arguments
String consumerKey = apiKeys[0];
String consumerSecret = apiKeys[1];
String token = apiKeys[2];
String secret = apiKeys[3];
// Store the configuration
ConfigurationBuilder config = new ConfigurationBuilder();
config.setDebugEnabled(true);
config.setOAuthConsumerKey(consumerKey);
config.setOAuthConsumerSecret(consumerSecret);
config.setOAuthAccessToken(token);
config.setOAuthAccessTokenSecret(secret);
config.setJSONStoreEnabled(true);
// Create a status listener. When a new tweet arives, the function object will accept it.
StatusListener listener = new TwitterStatusListener(fn);
// Create the filter. Can filter:
// * by Users (follow[])
// * by Stopword (track[])
// * by Location (locations[][])
// * by Language (language[])
FilterQuery filter = new FilterQuery();
filter.track(stopwords);
filter.follow(users);
filter.locations(coordinates);
// Create the stream-object
// Documentation: http://twitter4j.org/javadoc/twitter4j/TwitterStream.html
TwitterStream stream = new TwitterStreamFactory(config.build()).getInstance();
stream.addListener(listener);
stream.filter(filter);
}
}
我编写了一些代码,使用Query而不是FilterQuery作为搜索。但是我很难用另一个替换一个。
我的搜索代码如下:
public class TweetGetter {
/**
* @param response
*/
public void searchTwitter(String searchString) {
/*
* The TwitterFactory is what interacts directly with Twitter
*/
ConfigUtil twitterConfig = new ConfigUtil();
TwitterFactory tf = new TwitterFactory(twitterConfig.configureTwitter().build());
Twitter twitter = tf.getInstance();
Scanner scan = new Scanner (System.in);
// The factory instance is re-useable and thread safe.
try {
Query query = new Query();
query.setLang("en");
// query.setCount(10);
query.setQuery(searchString);
double lat = 28.6538100;
System.out.println();
double lon =77.2289700;
System.out.println();
//GeoLocation gl = new GeoLocation(28.6538100, 77.2289700);
GeoLocation gl = new GeoLocation(lat, lon);
double rad = 1000;
System.out.println();
//query.setGeoCode(gl, 1500, Query.KILOMETERS);
query.setGeoCode(gl, rad, Query.KILOMETERS);
query.setLang("en");
query.setCount(500);
// The object the will contain the results of the query
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
SaveUtil saver = new SaveUtil();
saver.saveTweets(tweets);
} while ((query = result.nextQuery()) != null);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
// System.exit(-1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scan.close();
}
}
其中saveUtil只是将数据保存在文本文件中。
无论如何我可以修改搜索代码来替换TweetStreamer吗?