java - 是否可以将推文存储在 csv 文件中?

标签 java twitter4j

已成功获取超过 100 条推文,但现在我无法将这些推文存储在 .csv 文件中? 尝试过文件处理类,那么如何存储推文?

public class SentimentAnalysisWithCount {

DoccatModel model;
static int positive = 0;
static int negative = 0;

public static void main(String[] args) throws IOException, TwitterException {
    String line = "";
    SentimentAnalysisWithCount twitterCategorizer = new SentimentAnalysisWithCount();
    twitterCategorizer.trainModel();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
        .setOAuthConsumerKey("--------------------------------------------------")
        .setOAuthConsumerSecret("--------------------------------------------------")
        .setOAuthAccessToken("--------------------------------------------------")
        .setOAuthAccessTokenSecret("--------------------------------------------------");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    Query query = new Query("udta punjab");
    QueryResult result = twitter.search(query);
    int result1 = 0;
    for (Status status : result.getTweets()) {
        result1 = twitterCategorizer.classifyNewTweet(status.getText());
        if (result1 == 1) {
            positive++;
        } else {
            negative++;
        }
    }

    BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\results.csv"));
    bw.write("Positive Tweets," + positive);
    bw.newLine();
    bw.write("Negative Tweets," + negative);
    bw.close();
}

public void trainModel() {
    InputStream dataIn = null;
    try {
        dataIn = new FileInputStream("C:\\Users\\User\\Downloads\\tweets.txt");
        ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
        ObjectStream sampleStream = new DocumentSampleStream(lineStream);
        // Specifies the minimum number of times a feature must be seen
        int cutoff = 2;
        int trainingIterations = 30;
        model = DocumentCategorizerME.train("en", sampleStream, cutoff,
                trainingIterations);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (dataIn != null) {
            try {
                dataIn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

public int classifyNewTweet(String tweet) throws IOException {
    DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
    double[] outcomes = myCategorizer.categorize(tweet);
    String category = myCategorizer.getBestCategory(outcomes);

    System.out.print("-----------------------------------------------------\nTWEET :" + tweet + " ===> ");
    if (category.equalsIgnoreCase("1")) {
        System.out.println(" POSITIVE ");
        return 1;
    } else {
        System.out.println(" NEGATIVE ");
        return 0;
    }

}
}

在此代码中,控制台上显示的推文应存储在 .csv 文件中

最佳答案

请从 Stackoverflow 中删除您的 API key 。您不应公开发布它们。

可以将推文存储在 CSV 中,您只需通过调整书面输出来增强您发布的代码片段。以下代码片段应该给出有关如何在 Java 8 中实现它的想法:

    try(BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\results.csv"))) {

    int positive = 0;
    int negative = 0;

    StringBuilder sb = new StringBuilder();
    for (Status status : result.getTweets()) {
        String tweetText = status.getText();
        long tweetId = status.getId();
        int classificationResult = twitterCategorizer.classifyNewTweet(tweetText);

        if (classificationResult == 1) {
            positive++;
        } else {
            negative++;
        }       

        sb.append("ID=").append(tweetId).append(",TEXT=").append(tweetText).append(",classificationResult=").append(classificationResult);

        String csvText = sb.toString();

        bw.write(csvText);
        bw.newLine();

        sb.delete(0,csvText);

    }

    bw.write("##### SUMMARY #####")
    bw.write("Positive Tweets," + positive);
    bw.newLine();
    bw.write("Negative Tweets," + negative);
    bw.close();

    }catch(IOException e) {
         //TODO Exception Handling
    }

results.csv 看起来像:

ID=25125125,TEXT=some fancy text here,classificationResult=1
ID=25146734725,TEXT=some fancy text1 here,classificationResult=0
ID=25127575125,TEXT=some fancy text2 here,classificationResult=1
ID=251258979125,TEXT=some fancy text3 here,classificationResult=0
ID=25125867125,TEXT=some fancy text4 here,classificationResult=1
##### SUMMARY #####
Positive Tweets,3
Negative Tweets,2

关于java - 是否可以将推文存储在 csv 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42573710/

相关文章:

java - 将 MM-DD-YYYY 表示为日、月日期

java - 在查询执行期间提供的参数列表中找不到查询参数 foo

Android 与 Twitter 的连接 - 从 twitter 获取空答案

java - 我如何将其变成一个简单的程序来接受 5 个数字并说出最小和最大?

java - eclipse : Packaging a JAR with natives

java - twitter4j 4.0.2 java.lang.NoClassDefFoundError : com/squareup/okhttp/OkHttpClient

android - 将 Twitter4j 状态转换为 JSON 对象

android - verifyCredentials 上的 Twitter4J 异常

java - 如何使用 twitter4j 获取更多推文并解析为 json?

java - javap 是否缺少一些行号?