打工人打工魂,打工的必会java调用python的几种用法
在java类中直接执行python语句
准备工作:
创建maven工程,结构如下:到官网https://www.jython.org/download.html下载Jython的jar包或者在maven的pom.xml文件中加入如下代码:
<dependency>java
<groupId>org.python</groupId> <artifactId>jython-standalone</artifactId> <version>2.7.0</version></dependency>
创建JavaRunPython.java类:
import org.python.util.PythonInterpreter;public class JavaRunPython { public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a='hello world'; ");
interpreter.exec("print a;");
}
}
2.在java中直接调用python脚本
在本地的D盘创建一个python脚本,文件名字为javaPythonFile.py,文件内容如下:
a = 1
b = 2
print (a + b)
创建JavaPythonFile.java类,内容如下:
import org.python.util.PythonInterpreter;public class JavaPythonFile { public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:\\javaPythonFile.py");
}
}
输出结果如下:
注意:以上两个方法虽然都可以调用python程序,但是使用Jpython调用的python库不是很多,如果你用以上两个方法调用,而python的程序中使用到第三方库,这时就会报错java ImportError: No module named xxx。遇到这种情况推荐使用下面的方法,即可解决该问题。
3.使用Runtime.getRuntime()执行python脚本文件,推荐使用
为了验证该方法可以运行含有python第三方库的程序,在本地的D盘创建一个python脚本,文件名字为demo1.py,代码如下:
import numpy as np
a = np.arange(12).reshape(3,4)print(a)
可以看到程序中用到了numpy第三方库,并初始化了一个3×4的一个矩阵。
下面来看看怎么用Runtime.getRuntime()方法来调用python程序并输出该结果,java代码如下:
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Demo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub Process proc;
try {
proc = Runtime.getRuntime().exec("python D:\\demo1.py");// 执行py文件 //用输入输出流来截取结果 BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出的结果如下图所示:
可以看到运行成功了,但有的朋友可能会问了,怎么在python程序中函数传递参数并执行出结果,下面我就举一例来说明一下。
先写一个python的程序,代码如下:
import sys
def func(a,b): return (a+b)if __name__ == '__main__':
a = []
for i in range(1, len(sys.argv)):
a.append((int(sys.argv[i])))
print(func(a[0],a[1]))
其中sys.argv用于获取参数url1,url2等。而sys.argv[0]代表python程序名,所以列表从1开始读取参数。
以上代码实现一个两个数做加法的程序,下面看看在java中怎么传递函数参数,代码如下:
int a = 18;
int b = 23;try {
String[] args1 = new String[] { "python", "D:\\demo2.py", String.valueOf(a), String.valueOf(b) };
Process proc = Runtime.getRuntime().exec(args1);// 执行py文件 BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
在来一个实战案例---模型获取相似关键词:
调用pyhon模型
java代码
package com.hadoop.flowsum;/*作者 :XiangLin
创建时间 :2020/10/26 9:55
文件 :testpython.java
IDE :IntelliJ IDEA
*/import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set;public class Demo1 {
public static String getType(Object o){ //获取变bai量类型方法du return o.getClass().toString(); //使用int类型的getClass()方法 }
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub String cmds = String.format("python D:word2vec\\testsimilar.py %s","中国");
Process pcs = Runtime.getRuntime().exec(cmds);
pcs.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(pcs.getInputStream(),"GB2312"));
Map<String, String> map = new HashMap<>();
String line = null;// System.out.println(in.readLine()); while ((line = in.readLine()) != null) {
System.out.println(line);
String[] s = line.split("\t");// System.out.println(s[0]+s[1]); map.put(s[0],s[1]);
}// System.out.println(in.readLine()); if (in.readLine() == null){
System.out.println("yes hhhhhh");
}// String key1 = (String) map.keySet().toArray()[0]; String key1 = (String) map.keySet().toArray()[0];
String d1 = map.get(key1);
double xx = Double.parseDouble(d1);// System.out.println(getType(xx));// if (xx > 0.6){// System.out.println("nice ................");// } }
}
python代码:
# * coding:utf-8_*_# 作者 :XiangLin# 创建时间 :2020/10/26 9:14# 文件 :testsimilar.py# IDE :PyCharmimport osimport timeimport warningsimport sys# import config# import loggingfrom gensim.models import Word2Vec# from gensim.models.word2vec import LineSentence, PathLineSentences# from pretreatment.pretreatment import PreDealwarnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
model = Word2Vec.load(r"D:\\model\\word2vec.model")def similarwords(keyword, tops=5): # 默认获取前10个相似关键词 start = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
# print("start execute Word2vec, get similar keywords! Time:" + start +">>>>>>>>>>>>>>>>>>>>>") try:
# model = Word2Vec.load(modelpath) words = model.wv.most_similar(keyword, topn=tops)
except KeyError:
# print("word '%s' not in vocabulary" % keyword) return None end = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
if not words:
return None # res = [[item[0], item[1]] for item in words] # 相似关键词及其相似度 res = []
for word in words:
res.append([word[0], word[1]])
print(word[0], "\t", word[1])
# print("get similar keywords end!................... Time:" + end + ">>>>>>>>>>>>>>>>>>>>>") # print(res) return resif __name__ == '__main__':
word = sys.argv[1];
similarwords(word)
输出:
最后
感谢大家看到这里,文章有不足,欢迎大家指出;如果你觉得写得不错,那就给我一个赞吧。
也欢迎大家关注我的公众号:程序员麦冬,每天更新行业资讯!
- Java中调用python的几种方式
- Java中调用Python并得到输出的用法
- Java代码调用python的几种方法
- Java中调用Python的几种方法
- java调用python
- Python可调用对象__call__方法的用法分析
- Python正则表达式的几种匹配用法
- [zz]使用thrift做c++,java和python的相互调用
- python调用Java-JPype使用介绍(一)(转)
- java调用dll的几种方法
- java 调用webservice的几种方法
- java 几种远程服务调用协议的比较
- 基于XML-RPC的远程调用(Python,Java)
- 在Java中调用Python
- Java中super的几种用法并与this的区别
- JAVA使用XFire开发Web Service客户端几种调用方式
- python中print的几种用法
- 在Java中调用Python
- Java调用Ant API用法收集
- python,java和php派生类调用父类方法说明