我尝试使用 OpenNLP 库来使用其句子检测器,并尝试编写以下代码,但出现与此 en-sent.bin 文件的地址相关的异常,但我没有知道如何处理该文件。
import java.io.*;
import java.net.URL;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
public class SentenceDetect
{
private SentenceDetectorME sentenceDetector;
public void init()
{
/** Load and initialize the sentence detection model */
InputStream modelIn = null;
SentenceModel model = null;
try {
modelIn = SentenceDetect.class.getClassLoader().getResourceAsStream("Tokenizer/models/en-sent.bin");
model = new SentenceModel(modelIn); //*<- line 36*
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
if (modelIn != null) {
try {
modelIn.close();
}
catch (IOException e) {}
}
}
sentenceDetector = new SentenceDetectorME(model);
}
public String[] getSentences(String longSentence)
{
return sentenceDetector.sentDetect(longSentence);
}
}
主类:
public static void main(String[] args)
{
SentenceDetect d = new SentenceDetect();
d.init(); ///*<- line 10*
String[] s = d.getSentences("This is sentence #1. This is Sentence #2");
System.out.println( s[0] ); // Should be the first sentence
System.out.println( s[1] ); // Should be the second sentence
}
下图显示了我的项目的层次结构(抱歉这张图片我使用 Ubuntu,但我不知道这里是否使用了打印屏幕按钮):
整个错误是:
`Exception in thread "main" java.lang.IllegalArgumentException: in must not be null!
at opennlp.tools.util.model.BaseModel.<init>(BaseModel.java:179)
at opennlp.tools.sentdetect.SentenceModel.<init>(SentenceModel.java:95)
at SentenceDetect.init(SentenceDetect.java:36)
at Main.main(Main.java:10)`
我尝试了这些路径,但遇到了同样的错误:
- /Tokenizer/models/en-sent.bin
- /models/en-sent.bin
- models/en-sent.bin
- /home/suri/workspace/2/Tokenizer/models/en-sent.bin
最佳答案
您需要将路径更改为
.getResourceAsStream("en-sent.bin");
由于 getResourceAsStream 读取了一个包,并且这些文件 (.bin) 位于您的源文件夹中。
关于java - 线程中的异常 "main"java.lang.IllegalArgumentException : in must not be null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35211811/