Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 是否可以将推文存储在csv文件中?_Java_Twitter4j - Fatal编程技术网

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

Java 是否可以将推文存储在csv文件中?,java,twitter4j,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 { S

成功获取了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;
    }

}
}

在此代码中,控制台上显示的tweet应存储在.csv文件中,请从Stackoverflow中删除API密钥。你不应该在公共场合发布它们

将tweet存储在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

向我们展示您的代码和卡在哪里。请将其添加到您的问题中,而不是作为注释。现在不可读了。在上面的代码中,每个tweet作为字符串应该存储在.csv文件中