JNI seems to have to use CPython, so py4j is a good idea. A guy who starts java in another process and bridges with python by socket communication.
I tried it with kuromoji
and my own jar.
I mean, I was happy that I could use kuromoji
from python, so I tried various things.
py4j0.8.2.1.jar
from py4j and prepare it.kuromoji-0.7.7.jar
readyorg/kuryu/Sample.java
package org.kuryu;
public class Sample {
public String foo() {
return "FOO!!!!!!!!";
}
public static String bar() {
return "BAR!!!!!!!!";
}
}
Make it a jar
$ javac org/kuryu/Sample.java
$ jar cvf kuryu.jar org/kuryu/*.class
J4Py.java
import py4j.GatewayServer;
public class J4Py {
public static void main(String[] args) {
J4Py app = new J4Py();
GatewayServer server = new GatewayServer(app);
server.start();
}
}
Add your own jar and kuromoji to the manifest.
manifest.mf
Main-Class: J4Py
Class-Path: py4j0.8.2.1.jar kuromoji-0.7.7.jar kuryu.jar
Make it a jar
$ javac -cp py4j0.8.2.1.jar J4Py.java
$ jar cvfm J4Py.jar manifest.mf J4Py.class
If you start it through the classpath, it seems that you can also use it from the py4j side.
When starting with jar
$ java -jar J4Py.jar
When starting with class
$ java -cp py4j0.8.2.1.jar:kuromoji-0.7.7.jar:kuryu.jar:. J4Py
With the Java Gateway Server running, do this.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()
# java.util.Random
random = gateway.jvm.java.util.Random()
n1 = random.nextInt(10)
n2 = random.nextInt(10)
print "%d + %d = %d" % (n1, n2, n1+n2)
#Self-made jar
kuryu = gateway.jvm.org.kuryu.Sample
print kuryu.bar()
ins = kuryu()
print ins
print ins.foo()
#kuromoji Tokenizer
KuroTokenizer = gateway.jvm.org.atilika.kuromoji.Tokenizer
tokenizer = KuroTokenizer.builder().build();
a = tokenizer.tokenize(u"I want to eat sushi.")
for token in a:
print token.getSurfaceForm() + "\t" + token.getAllFeatures()
Mainly this strange.
http://www.atilika.com/ja/products/kuromoji.html http://py4j.sourceforge.net/py4j_java_gateway.html http://qiita.com/mojaie/items/f16b97b1388f73e56b86
Recommended Posts