Java调用Python和R代码

在项目中Java程序编写使用的是IDEA,无论是调用Python程序还是R程序,都需要保证电脑上已经安装了Python和R的编程软件;将Python和R的安装路径添加至电脑的环境变量中。
对于调用Python程序,需要在IDEA中添加Python的安装路径作为环境变量。
Java调用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])))     # caution:int or str
    print(func(a[0],a[1]))

其中sys.argv用于获取参数url1,url2等。而sys.argv[0]代表python程序名,所以列表从1开始读取参数。 下面看看在java中怎么传递函数参数,代码如下:

int a = 18;
int b = 23;
try {
    String[] args = new String[] { "python", "D:\\demo2.py", String.valueOf(a), String.valueOf(b) };
    Process proc = Runtime.getRuntime().exec(args);// 执行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();
}

Java调用R方法:
调用R文件中自定义函数,创建R文件test.R。

myFunc<-function(data){
    x<-data+2;
}

package com.rTest;

import org.rosuda.REngine.REXP;
import org.rosuda.REngine.Rserve.RConnection;

RConnection rc = new RConnection();
// test.R的路径
String fileName = "D:\\test.R";
rc.assign("fileName", fileName);
//执行test.R脚本,执行这一步才能调用里面的自定义函数myFunc,如果不行,就在R工具上也执行一下test.R脚本
rc.eval("source(fileName)");
String num = "3";
//调用myFunc函数
REXP rexp=rc.eval("myFunc("+num+")");
//返回类型是一个整数类型,所以用asInteger
System.out.println(rexp.asInteger());
rc.close();//用完记得关闭连接

参考资料:
https://blog.csdn.net/qq_26591517/article/details/80441540
https://blog.csdn.net/tyhj_sf/article/details/81320731

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值