• jython实现java运行python代码


    Jython是一种完整的语言,而不是一个Java翻译器或仅仅是一个Python编译器,它是一个Python语言在Java中的完全实现。最近的一个项目需要将python代码转换成java实现,所以用了一下jython。

    试用了jython的2.7的版本发现运行一直出错,不知道是不是版本的原因,但是2.5的版本还是可以的。

    第一步,先来一个简单的(先确定你已经下载添加了对应的jar包)

    java代码:

    PythonInterpreter interpreter = new PythonInterpreter();  
    interpreter.execfile(
    "/home/桌面/PycharmProjects/first/1.py");

    python代码:

    print("hello jython")

    输出:

    第二步:调用方法(不含参数)

    java代码:

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("/home/ybf/PycharmProjects/first/1.py");
    PyFunction func_first = (PyFunction)interpreter.get("first",PyFunction.class);
    PyFunction func_second= (PyFunction)interpreter.get("second",PyFunction.class);
    PyObject pyobj = func_second.__call__();
    System.out.println(pyobj);

    python代码:

    def first():
    print("first ...........")

    first()

    def second():
    a=100
    b=50
    return a+b

    输出:

    第三步:调用方法(含参数)

    java代码:

    PythonInterpreter interpreter = new PythonInterpreter(); 
    interpreter.execfile("/home/ybf/PycharmProjects/first/1.py"); 

    PyFunction func_third= (PyFunction)interpreter.get("third",PyFunction.class); 

    PyObject pyobj = func_third.__call__(new PyInteger(4), new PyInteger(2));
    System.out.println(pyobj);

    python代码:

    def third(a,b):
    c=sub(a,b)
    d=sub(b,a)
    return c*d

    def sub(a,b):
    return a-b

    输出:

    第四步:关于中文处理,这是一个很麻烦的方面,大家可以看下面的例子

    java代码:

    String a = "你好";  
    PyFunction func= (PyFunction)interpreter.get("word_process",PyFunction.class);
    PyObject pyobj = func.__call__(new PyString(a));  
    System.out.println(pyobj.toString());

    python代码:

    def word_process(a):
        if a=="你好":                                                                                                           
            print(True)
        else:
            print(False)
        print(a)
        return a 

    结果:

    这里可以看到在Python里面输出在eclipse输出的是?,其实输出的是“你好”,但是因为平台的原因所以显示?(个人的理解),而且大家可以发现在python中的“你好”不等于java里面的“你好”,这方面本人还不知道,不知道有没有大佬知道,怎样处理才返回True,

    str(a).encode('utf-8')=="你好".encode("utf-8")这样返回的也是False

    第五步:打开txt文本

    这里注意python里面的代码,如下:

    f=open('src/dic/v.txt','rt')#注意文件路径
    while(True):
        line=f.readline()
        if not line:
            break
        print(line)

    如果这里使用 with open('src/dic/v.txt','rt') as f 但在eclipse报错如下:

     今天写到这里,有时间再更新 

  • 相关阅读:
    实例下载
    js跳转
    navicat怎么导出和导入数据表
    navicate怎么用sql语句插入一条语句
    svn提交时出现很多乱文件怎么解决
    随机显示星星(点击可删除)
    html节点属性操作
    利用节点更改table内容
    TreeView添加treeView1_NodeMouseClick----多么痛的领悟。。。
    IP addresses in C#
  • 原文地址:https://www.cnblogs.com/ybf-yyj/p/8344139.html
Copyright © 2020-2023  润新知