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)
Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。
Rocky Linux
Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。
Sublime Text
Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。