[英]Use PythonInterpreter with Jython in Java Code
When I type jython in terminal I get: 在终端中输入jython时,我得到:
Jython 2.2.1 on java1.7.0_51
I want to use the NLTK POS in my java code. 我想在我的Java代码中使用NLTK POS。 I followed @Vicent answer in how to add module of python into java using jython jar to use python interpreter, 我跟随@Vicent回答如何使用jython jar将python 模块添加到java中以使用python解释器,
package myjythonproject;
import org.python.util.PythonInterpreter;
public class MyJythonProject {
public static void main(String[] args) {
try
{
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("/home/vicent/foo.py");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
with only one change on the code: 只需对代码进行一次更改:
interp.execfile("/Users/ha/Desktop/Code.py");
there is no error but the content of Code.py is not displayed(which is only printing Hello world). 没有错误,但是Code.py的内容未显示(仅打印Hello world)。
if __name__ == "__main__":
print "Hello World";
I've edit the system path from terminal to the jython lib folder. 我已经编辑了从终端到jython lib文件夹的系统路径。
How can I make it work? 我该如何运作?
UPDATE: 更新:
After I added print __name__
before the if statement - As suggested by @MikeRixWolfe - and I got this output: 在if语句之前添加print __name__
之后(如@MikeRixWolfe所建议),得到以下输出:
run:
main
BUILD SUCCESSFUL (total time: 1 second)
so I edit it to if __name__ == "main":
and it works! 所以我将其编辑为if __name__ == "main":
并且可以使用!
Likely the __name__
is not __main__
due to it being called from the java program, rather than directly. __name__
可能不是 __main__
因为它是从Java程序而非直接调用的。 Try placing print __name__
above the if
statement to verify 尝试将print __name__
放在if
语句上方以进行验证
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.