首页 > 解决方案 > 将参数从python发送到java时出现无法识别的错误

问题描述

我正在尝试将参数从我的 java GUI 传递给 python 算法。我尝试了很多方法,但我不断收到无法识别的参数作为错误。我正在使用 Process builder 将 python 代码集成到我的 java 中。我需要将 fav_movie 从 java 发送到 python。

这是python代码的一部分。我是一个python初学者,所以如果你能告诉我是什么导致这个错误会很有帮助

  def _fuzzy_matching(self, hashmap, fav_movie):
        """
        return the closest match via fuzzy ratio.
        If no match found, return None
        Parameters
        ----------
        hashmap: dict, map movie title name to index of the movie in data
        fav_movie: str, name of user input movie
        Return
        ------
        index of the closest match
        """
        match_tuple = []
        # get match
        for title, idx in hashmap.items():
            ratio = fuzz.ratio(title.lower(), fav_movie.lower())
            if ratio >= 60:
                match_tuple.append((title, idx, ratio))
        # sort
        match_tuple = sorted(match_tuple, key=lambda x: x[2])[::-1]
        if not match_tuple:
            print('Oops! No match is found')
        else:
            print('Found possible matches in our database: '
                  '{0}\n'.format([x[0] for x in match_tuple]))
            return match_tuple[0][1]
def parse_args():
    parser = argparse.ArgumentParser(
        prog="Movie Recommender",
        description="Run KNN Movie Recommender")
    parser.add_argument('--path', nargs='?', default='C:\java programs\qcri 3\ml-latest-small',
                        help='input data path')
    parser.add_argument('--movies_filename', nargs='?', default='movies.csv',
                        help='provide movies filename')
    parser.add_argument('--ratings_filename', nargs='?', default='ratings.csv',
                        help='provide ratings filename')
    parser.add_argument('--movie_name', nargs='?', default='',
                        help='provide your favourite movie name')
    parser.add_argument('--top_n', type=int, default=10,
                        help='top n movie recommendations')
    return parser.parse_args()


if __name__ == '__main__':
    # get args
    args = parse_args()
    data_path = args.path
    movies_filename = args.movies_filename
    ratings_filename = args.ratings_filename
    movie_name = args.movie_name
    top_n = args.top_n
    # initial recommender system
    recommender = KnnRecommender(
        os.path.join(data_path, movies_filename),
        os.path.join(data_path, ratings_filename))
    # set params
    recommender.set_filter_params(50, 50)
    recommender.set_model_params(20, 'brute', 'cosine', -1)
    # make recommendations
    recommender.make_recommendations(movie_name, top_n)

这是显示的错误:

usage: Movie Recommender [-h] [--path [PATH]]
                         [--movies_filename [MOVIES_FILENAME]]
                         [--ratings_filename [RATINGS_FILENAME]]
                         [--movie_name [MOVIE_NAME]] [--top_n TOP_N]
Movie Recommender: error: unrecognized arguments: toy

这是访问python的java代码:


    public static void main(String args[]) throws ScriptException, InterruptedException
    {


        System.out.println("enter movie name");
        Scanner s= new Scanner(System.in);
        String name= s.nextLine();

         ProcessBuilder pb= new ProcessBuilder("python","recomold.py",name);
         System.out.println("running file");
         Process process = null;
        try {
            process = pb.start();
            inheritIO(process.getInputStream(), System.out);
            inheritIO(process.getErrorStream(), System.err);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         int err= process.waitFor();
         System.out.println("any errors?"+(err==0 ? "no" : "yes ")+err);
         try {
            System.out.println("python output "+ output(process.getInputStream()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

   }

    private static void inheritIO(InputStream src, PrintStream dest) {
         new Thread(new Runnable() {
                public void run() {
                    Scanner sc = new Scanner(src);
                    while (sc.hasNextLine()) {
                        dest.println(sc.nextLine());
                    }
                }
            }).start();
    }

    private static String output(InputStream inputStream) throws IOException {
            StringBuilder sb = new StringBuilder();
            BufferedReader br = null;
            try{
                br= new BufferedReader(new InputStreamReader(inputStream));
                String line = null;
                while((line=br.readLine())!=null)
                {
                    sb.append(line+"\n");
                }
            }
            finally
            {
                br.close();
            }
            return sb.toString();
    } 
}

标签: javapython

解决方案


看起来您的 Python 脚本不接受非选项参数作为正确输入。根据 Python 程序的帮助文本,您提供的任何参数都必须以选项/值对形式出现,如下所示:

--<option_name> <option_value>

但是您只是传递没有选项说明符的“玩具”。所以也许你想要的是在你的 Java 代码中是这样的:

ProcessBuilder pb= new ProcessBuilder("python","recomold.py","--movie-name",name);

推荐阅读