publicstaticvoidmain(String[] args){ PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("D:\\javaPythonFile.py"); } }
输出结果如下:
注意:以上两个方法虽然都可以调用python程序,但是使用Jpython调用的python库不是很多,如果你用以上两个方法调用,而python的程序中使用到第三方库,这时就会报错java ImportError: No module named xxx。遇到这种情况推荐使用下面的方法,即可解决该问题。
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 os import time import warnings import sys # import config # import logging from gensim.models import Word2Vec # from gensim.models.word2vec import LineSentence, PathLineSentences # from pretreatment.pretreatment import PreDeal warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim') model = Word2Vec.load(r"D:\\model\\word2vec.model")
defsimilarwords(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) returnNone end = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) ifnot words: returnNone # 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 res
if __name__ == '__main__': word = sys.argv[1]; similarwords(word)