简体   繁体   English

Twitter API 应用逻辑

[英]Twitter API with a Logic applied to it

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 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.我设法使用 Twitter 4j API 获得了 Twitter 帖子,但我不知道如何计算最后 5 条推文的每条推文的平均字数。

Can anyone help me understand how to do this please?谁能帮我理解如何做到这一点?

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);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM