Twitter API with a Logic applied to it

前提是你 提交于 2020-04-18 06:11:05

问题


I am a beginner in Java programming and I have an assignment where I need to get posts from the Twitter API and implement a logic using Eclipse Java Photon.

I managed to get the Twitter posts using Twitter 4j API but I am stuck of how to calculate the average words per tweet for the last 5 tweets.

Can anyone help me understand how to do this please ?


回答1:


You can get tweet contents and then split them into words. After that you can get average word count by counting the words and dividing it to tweet count.

This code may help you to achieve that logic:


public class Solution {
    public static void main(String args[]) {
        Solution.printAverageWordCount();
    }

    public static void printAverageWordCount(){
        Query query = new Query("");
        query.setCount(100);
        query.setResultType(Query.RECENT);

        int statusLimit = 5;
        int wordCount = 0;
        int tweetCount;

        do {
            QueryResult result = twitter.search(query);
            statuses = result.getTweets();
            System.out.prinln("Fetch " + statuses.size() + " statuses. Completed in: " + result.getCompletedIn());

            tweetCount = 0;

            for (Status status : statuses) {
                wordCount += status.getText().split("\\s+").length;
                tweetCount++;
                if(tweetCount >= statusLimit) {
                    break;
                }
            }

            query = result.nextQuery();
        } while (tweetCount < statusLimit);


        // calculate average

        double average = wordCount/(double)tweetCount;
        System.out.println(average);
    }

}


来源:https://stackoverflow.com/questions/61237725/twitter-api-with-a-logic-applied-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!