Как передать 2d массив в Java Main из ReactJS? - PullRequest
0 голосов
/ 13 октября 2018

У меня есть две программы, одна на ReactJS и одна на Java, и мне нужно передать 2d-массив из ReactJS в основную часть Java, но я не понимал, что не могу изменить основную сигнатуру public static void main(String[] args) {}, чтобы принятьit.

Я видел подобные вопросы вокруг, но они в основном касаются передачи многомерных массивов вокруг методов в целом, которые настроены внутри метода, но должны передавать что-то вроде:

[["1", "string", "1.0"], ["2", "string", "2.0"]]

... но не могу быть уверен, что мне нужно выбраться.Это только добавит к строковым элементам в середине, поэтому будет что-то вроде:

[["1", "string", "string", "1.0"], ["2", "string", "string", "string", "2.0"]]

Итак, просто повторюсь, как я могу передать в 2d массив (зная,насколько большим будет внутренний массив) и вернет двумерный массив (не зная, насколько большими будут внутренние массивы)?

Мой класс Java выглядит следующим образом ...

import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * This class takes a parameter (review) through the main args and runs it through the sentiment analysis.
 * Where necessary, the analysis breaks the review into shorter sentences and scores each one.
 * If devMode is set to TRUE, the detailed output is displayed in the console.
 * The average of the review sentiments are then returned as a type double.
 */
public class SentimentAnalysis {

    private static ArrayList findSentiment(ArrayList<String[]> allReviews) {
        // Set to TRUE to display the breakdown of the output to the console
        boolean devMode = false;

        ArrayList<List> scoredReviewsArray = new ArrayList<>();
        double totalSentimentScore = 0;
        int counter = 1;

        // Setup Stanford Core NLP package
        Properties props = new Properties();
        props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
        StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

        if (devMode) {
            System.out.println("" +
                    "\n==============================================================================================================\n" +
                    "The output shows the sentiment analysis for the comment provided.\n" +
                    "The StanfordCoreNlp algorithm breaks apart the input and rates each section numerically as follows:\n" +
                    "\n" +
                    "\t1 = Negative\n" +
                    "\t2 = Neutral\n" +
                    "\t3 = Positive\n" +
                    "\n" +
                    "The returned value is the average of all the sentiment ratings for the provided comment.\n" +
                    "==============================================================================================================\n"
            );
        }

        for (String[] singleReview : allReviews) {
            ArrayList<String> review = new ArrayList<>();
            String reviewId = singleReview[0];
            review.add(reviewId);

            double sentimentSectionScore;

            String reviewText = singleReview[1];

            if (reviewText != null && reviewText.length() > 0) {

                Annotation annotation = pipeline.process(reviewText);

                for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) {
                    Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);

                    sentimentSectionScore = RNNCoreAnnotations.getPredictedClass(tree);

                    totalSentimentScore += sentimentSectionScore;

                    if (devMode) {
                        System.out.println("\nSentence " + counter++ + ": " + sentence);
                        System.out.println("Sentiment score: " + sentimentSectionScore);
                        System.out.println("Total sentiment score: " + totalSentimentScore);
                    }

                    review.add(sentence.toString());
                    review.add(String.valueOf(sentimentSectionScore));
                }

                scoredReviewsArray.add(review);
            }
        }

        System.out.println(scoredReviewsArray.toString());

        return scoredReviewsArray;
    }

    public static void main(String[] args) {

        // Test array of review arrays
        String mockReview1[] = {"1", "String 1.1. String 1.2.", ""};
        String mockReview2[] = {"2", "String 2", ""};
        String mockReview3[] = {"3", "String 3", ""};
        ArrayList<String[]> reviews = new ArrayList<>();
        reviews.add(mockReview1);
        reviews.add(mockReview2);
        reviews.add(mockReview3);

        findSentiment(reviews);

    }
}

... и я оборачиваю свое Java-приложение в Jar для передачи и извлечения данных из ReactJS с помощью дочернего процесса следующим образом:

const exec = require('child_process').spawn('java', ['-jar', './StanfordNlp.jar', allReviews]);

    exec.stdout.on('data', function (data) {
        // Do stuff...
    });

Надеюсь, что все это имеет смысл, если вам нужномне, чтобы уточнить что-нибудь, пожалуйста, просто спросите.

Ваша помощь очень ценится.

Спасибо!

...