日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

java语言的编译器可以用python_jython实现java运行python代码

發(fā)布時間:2024/10/8 python 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java语言的编译器可以用python_jython实现java运行python代码 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Jython是一種完整的語言,而不是一個Java翻譯器或僅僅是一個Python編譯器,它是一個Python語言在Java中的完全實現(xiàn)。最近的一個項目需要將python代碼轉換成java實現(xiàn),所以用了一下jython。

試用了jython的2.7的版本發(fā)現(xiàn)運行一直出錯,不知道是不是版本的原因,但是2.5的版本還是可以的。

第一步,先來一個簡單的(先確定你已經下載添加了對應的jar包)

java代碼:

PythonInterpreter interpreter = newPythonInterpreter();

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__(newPyString(a));

System.out.println(pyobj.toString());

python代碼:

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

結果:

這里可以看到在Python里面輸出在eclipse輸出的是?,其實輸出的是“你好”,但是因為平臺的原因所以顯示?(個人的理解),而且大家可以發(fā)現(xiàn)在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 notline:break

print(line)

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

今天寫到這里,有時間再更新

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的java语言的编译器可以用python_jython实现java运行python代码的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。