Java调用Python返回乱码问题解决

python代码如下

#coding:utf-8

def keywordsRouter(keywords):  
    str = keywords+"这里是中文";
    print("py=="+str);
    return str;

java代码如下

Properties props = new Properties();
//      props.put("python.home","path to the Lib folder");
        props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
        props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses
        props.put("python.import.site","false");
        Properties preprops = System.getProperties();
        PythonInterpreter.initialize(preprops, props, new String[0]);
        PythonInterpreter interp = new PythonInterpreter();

        String ret = "";
        String pyfilePath = ".py文件的路径";
        interp.execfile(pyfilePath);  
        PyFunction func = (PyFunction)interp.get("keywordsRouter",PyFunction.class);  

        PyObject pyobj = func.__call__(new PyString("传给keywordsRouter方法的参数"));  
        ret = pyobj.toString();//这里ret可能会乱码
        String newStr = new String(ret.getBytes("iso8859-1"), "utf-8");  //通过new String(ret.getBytes("iso8859-1"), "utf-8")转一下就好了
        System.out.println("anwser= " +newStr);  //newStr就不会乱码了
        return newStr;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值