2022年 11月 3日

java调用python的几种方法(看这篇就够了)

关注公众号:任识算法,获取更多技术干货!

本文主要介绍了java调用python的几种方法。 

在java类中直接执行python语句

准备工作:

创建maven工程,结构如下:到官网https://www.jython.org/download.html下载Jython的jar包或者在maven的pom.xml文件中加入如下代码:

  1. <dependency>java
  2.     <groupId>org.python</groupId>
  3.     <artifactId>jython-standalone</artifactId>
  4.     <version>2.7.0</version>
  5. </dependency>

创建JavaRunPython.java类:

  1. import org.python.util.PythonInterpreter;
  2. public class JavaRunPython {
  3.     public static void main(String[] args) {
  4.         PythonInterpreter interpreter = new PythonInterpreter();
  5.         interpreter.exec("a='hello world'; ");
  6.         interpreter.exec("print a;");
  7.     }
  8. }

2.在java中直接调用python脚本

在本地的D盘创建一个python脚本,文件名字为javaPythonFile.py,文件内容如下:

  1. a = 1
  2. b = 2
  3. print (a + b)

创建JavaPythonFile.java类,内容如下:

  1. import org.python.util.PythonInterpreter;
  2. public class JavaPythonFile {
  3.     public static void main(String[] args) {
  4.         PythonInterpreter interpreter = new PythonInterpreter();
  5.         interpreter.execfile("D:\\javaPythonFile.py");
  6.     }
  7. }

输出结果如下:

注意:以上两个方法虽然都可以调用python程序,但是使用Jpython调用的python库不是很多,如果你用以上两个方法调用,而python的程序中使用到第三方库,这时就会报错java ImportError: No module named xxx。遇到这种情况推荐使用下面的方法,即可解决该问题。

3.使用Runtime.getRuntime()执行python脚本文件,推荐使用

为了验证该方法可以运行含有python第三方库的程序,在本地的D盘创建一个python脚本,文件名字为demo1.py,代码如下:

  1. import numpy as np
  2. a = np.arange(12).reshape(3,4)
  3. print(a)

可以看到程序中用到了numpy第三方库,并初始化了一个3×4的一个矩阵。

下面来看看怎么用Runtime.getRuntime()方法来调用python程序并输出该结果,java代码如下:

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. public class Demo1 {
  5.     public static void main(String[] args) {
  6.         // TODO Auto-generated method stub
  7.         Process proc;
  8.         try {
  9.             proc = Runtime.getRuntime().exec("python D:\\demo1.py");// 执行py文件
  10.             //用输入输出流来截取结果
  11.             BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
  12.             String line = null;
  13.             while ((line = in.readLine()) != null) {
  14.                 System.out.println(line);
  15.             }
  16.             in.close();
  17.             proc.waitFor();
  18.         } catch (IOException e) {
  19.             e.printStackTrace();
  20.         } catch (InterruptedException e) {
  21.             e.printStackTrace();
  22.         } 
  23.     }
  24. }

输出的结果如下图所示:

可以看到运行成功了,但有的朋友可能会问了,怎么在python程序中函数传递参数并执行出结果,下面我就举一例来说明一下。

先写一个python的程序,代码如下:

  1. import sys
  2. def func(a,b):
  3.     return (a+b)
  4. if __name__ == '__main__':
  5.     a = []
  6.     for i in range(1len(sys.argv)):
  7.         a.append((int(sys.argv[i])))
  8.     print(func(a[0],a[1]))

其中sys.argv用于获取参数url1,url2等。而sys.argv[0]代表python程序名,所以列表从1开始读取参数。

以上代码实现一个两个数做加法的程序,下面看看在java中怎么传递函数参数,代码如下:

  1. int a = 18;
  2. int b = 23;
  3. try {
  4.     String[] args1 = new String[] { "python""D:\\demo2.py"String.valueOf(a), String.valueOf(b) };
  5.     Process proc = Runtime.getRuntime().exec(args1);// 执行py文件
  6.     BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
  7.     String line = null;
  8.     while ((line = in.readLine()) != null) {
  9.         System.out.println(line);
  10.     }
  11.     in.close();
  12.     proc.waitFor();
  13. catch (IOException e) {
  14.     e.printStackTrace();
  15. catch (InterruptedException e) {
  16.     e.printStackTrace();
  17. }

在来一个实战案例—模型获取相似关键词:

调用pyhon模型

java代码

package com.hadoop.flowsum;/*
  1. 文件     :testpython.java
  2. IDE      :IntelliJ IDEA
  3. */
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.util.HashMap;
  8. import java.util.Iterator;
  9. import java.util.Map;
  10. import java.util.Set;
  11. public class Demo1 {
  12.     public static String getType(Object o){ //获取变bai量类型方法du
  13.         return o.getClass().toString(); //使用int类型的getClass()方法
  14.     }
  15.     public static void main(String[] args) throws IOExceptionInterruptedException {
  16.         // TODO Auto-generated method stub
  17.         String cmds = String.format("python D:word2vec\\testsimilar.py %s","中国");
  18.         Process pcs = Runtime.getRuntime().exec(cmds);
  19.         pcs.waitFor();
  20.         BufferedReader in = new BufferedReader(new InputStreamReader(pcs.getInputStream(),"GB2312"));
  21.         Map<StringString> map = new HashMap<>();
  22.         String line = null;
  23. //        System.out.println(in.readLine());
  24.         while ((line = in.readLine()) != null) {
  25.             System.out.println(line);
  26.             String[] s = line.split("\t");
  27. //            System.out.println(s[0]+s[1]);
  28.             map.put(s[0],s[1]);
  29.         }
  30. //        System.out.println(in.readLine());
  31.         if (in.readLine() == null){
  32.             System.out.println("yes hhhhhh");
  33.         }
  34. //        String key1 = (String) map.keySet().toArray()[0];
  35.         String key1 = (String) map.keySet().toArray()[0];
  36.         String d1 = map.get(key1);
  37.         double xx = Double.parseDouble(d1);
  38. //        System.out.println(getType(xx));
  39. //        if (xx > 0.6){
  40. //            System.out.println("nice   ................");
  41. //        }
  42.     }
  43. }

python代码:

  1. # * coding:utf-8_*_
  2. import os
  3. import time
  4. import warnings
  5. import sys
  6. # import config
  7. # import logging
  8. from gensim.models import Word2Vec
  9. # from gensim.models.word2vec import LineSentence, PathLineSentences
  10. # from pretreatment.pretreatment import PreDeal
  11. warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
  12. model = Word2Vec.load(r"D:\\model\\word2vec.model")
  13. def similarwords(keyword, tops=5):
  14.     # 默认获取前10个相似关键词
  15.     start = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  16.     # print("start execute Word2vec, get similar keywords! Time:" + start +">>>>>>>>>>>>>>>>>>>>>")
  17.     try:
  18.         # model = Word2Vec.load(modelpath)
  19.         words = model.wv.most_similar(keyword, topn=tops)
  20.     except KeyError:
  21.         # print("word '%s' not in vocabulary" % keyword)
  22.         return None
  23.     end = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  24.     if not words:
  25.         return None
  26.         # res = [[item[0], item[1]] for item in words]   # 相似关键词及其相似度
  27.     res = []
  28.     for word in words:
  29.         res.append([word[0], word[1]])
  30.         print(word[0], "\t", word[1])
  31.     # print("get similar keywords end!................... Time:" + end + ">>>>>>>>>>>>>>>>>>>>>")
  32.     # print(res)
  33.     return res
  34. if __name__ == '__main__':
  35.     word = sys.argv[1];
  36.     similarwords(word)

输出: