我正在使用 Twitter4j 构建一个客户端来获取输入搜索词的推文。我还试图为用户提供在结果中输入他想要的推文数量的设施。
我知道我们可以使用查询的 setCount()
方法设置每页返回的推文数量:
Query q = new Query(searchTerm);
q.setCount(maxTweets);
但是如果我将值 1 作为 maxTweets,它会返回 2 条推文。
更新:经过进一步研究,我发现每次搜索都会返回 1 条额外的推文。因此,我将 1 作为 maxTweets 值,它会返回 2 条推文。如果我给出 2 作为 maxTweets 值,它将返回 3 条推文,依此类推。
我不确定我错在哪里,但请告诉我是否有办法可以使用 twitter4j 获取固定数量的推文。
任何指导都会有所帮助。
最佳答案
当你写的时候
Query q = new Query(searchTerm);
将其视为一个表格页面,其中包含大量与您的查询匹配的结果。但可能会有更多的页面。
当你设置时
q.setCount(maxTweets);
它将为您带来每页 maxTweets
条推文数量。在您的例子中,为 2,因为有两个页面与您的查询匹配,并且您为每页选择了一条推文。
你能做什么,尝试用 do - while 循环来处理它。
Query q = new Query(searchTerm);
QueryResult result;
int tempUSerInput = 0; //keep a temp value
boolean flag = false;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
tempUSerInput = tempUSerInput + tweets.size();
if(tempUSerInput >= realyourUserInput) // you have already matched the number
flag = true; //set the flag
}
while ((query = result.nextQuery()) != null && !flag);
// Here Take only realyourUserInput number
// as you might have taken more than required
List<Status> finaltweets = new ArrayList();
for(int i=0; i<realyourUserInput; i++)
finaltweets.add( tweets.get(i) ); //add them to your final list
关于java - 如何使用 twitter4j 获取固定数量的推文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24849425/