为什么opennlp库的HelloWorld在Java上工作正常,但不适用于Jruby?

时间:2012-10-20 21:48:00

标签: java macos jruby opennlp

我收到此错误:

SyntaxError: hello.rb:13: syntax error, unexpected tIDENTIFIER
public HelloWorld( InputStream data ) throws IOException {

HelloWorld.rb是:

require "java"

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;

import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;

public class HelloWorld {
    private POSModel model;

    public HelloWorld( InputStream data ) throws IOException {
    setModel( new POSModel( data ) );
    }

    public void run( String sentence ) {
    POSTaggerME tagger = new POSTaggerME( getModel() );
    String[] words = sentence.split( "\\s+" );
    String[] tags = tagger.tag( words );
    double[] probs = tagger.probs();

    for( int i = 0; i < tags.length; i++ ) {
    System.out.println( words[i] + " => " + tags[i] + " @ " + probs[i] );
    }
    }

    private void setModel( POSModel model ) {
    this.model = model;
    }

    private POSModel getModel() {
    return this.model;
    }

    public static void main( String args[] ) throws IOException {
    if( args.length < 2 ) {
    System.out.println( "HelloWord <file> \"sentence to tag\"" );
    return;
    }

    InputStream is = new FileInputStream( args[0] );
    HelloWorld hw = new HelloWorld( is );
    is.close();

    hw.run( args[1] );
    }
}

运行ruby HelloWorld.rb "I am trying to make it work"

当我运行HelloWorld.java "I am trying to make it work"时,它完美无缺,当然.java不包含require java语句。

修改

我遵循了以下steps

jruby -v的输出:

jruby 1.6.7.2 (ruby-1.8.7-p357) (2012-05-01 26e08ba) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_35) [darwin-x86_64-java]

2 个答案:

答案 0 :(得分:1)

因为它是用Java而不是Ruby编写的?

答案 1 :(得分:1)

JRuby是Java中的ruby实现,这意味着如果你想使用JRuby,你必须使用ruby语法。您确实可以在JRuby中使用Java对象,但使用ruby语法 - 您无法使用Java语法。

例如,frame = javax.swing.JFrame.new("Window")使用JFrame,但使用ruby语法(即JFrame.new而不是new JFrame)。

因此您的代码将类似于:

require 'java'
# Require opennlp jars
Dir.glob('**/*.jar').each do |jar|
  require jar
end

java_import 'opennlp.tools.postag.POSTaggerME'
java_import 'opennlp.tools.postag.POSModel'

class HelloWorld
  def initialize(data)
    @model = POSModel.new(data)
  end

  def run(sentence)
    tagger = POSTaggerME.new(@model)
    words = sentence.split
    tags = tagger.tag(words)
    probs = tagger.probs

    probs.each_with_index do |p,i|
      puts "#{words[i]} => #{tags[i]} @ #{p}"
    end
  end
end

stream = File.new(ARGV[0]).to_java.getInStream
HelloWorld.new(stream).run(ARGV[1])

全部。红宝石。代码。