【问题标题】:OpenNLP Sentence Detection API for entire text file用于整个文本文件的 OpenNLP 句子检测 API
【发布时间】:2012-10-05 09:34:07
【问题描述】:

这是针对单个字符串的 OpenNLP Sentence Detector API 的代码:

package opennlp;

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

import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;

public class SentenceDetector {

    public static void main(String[] args) throws FileNotFoundException {
        InputStream modelIn = new FileInputStream("en-sent.zip");
        SentenceModel model = null;
        try {
           model = new SentenceModel(modelIn);  
        }
        catch (IOException e) {
          e.printStackTrace();
        }
        finally {
          if (modelIn != null) {
            try {
              modelIn.close();
            }
            catch (IOException e) {
            }
          }
        }
        SentenceDetectorME sentenceDetector = new SentenceDetectorME(model);
           String sentences[] = sentenceDetector.sentDetect(" First sentence. Second sentence.");

           for(String str : sentences)
               System.out.println(str);
    }
}

现在我的问题是如何传递整个文本文件并执行句子检测而不是单个字符串?

【问题讨论】:

  • 将文件读入字符串,然后像以前一样继续。
  • @AndrewThompson 看到最后一行
  • 不错的编辑。 +1 希望你能得到答案。 :)

标签: java string file opennlp


【解决方案1】:

简单的方法:将整个文件作为字符串读取并以通常的方式传递。以下方法将文件内容读取为字符串:

public String readFileToString(String pathToFile) throws Exception{
    StringBuilder strFile = new StringBuilder();
    BufferedReader reader = new BufferedReader(new FileReader(pathToFile));
    char[] buffer = new char[512];
    int num = 0;
    while((num = reader.read(buffer)) != -1){
        String current = String.valueOf(buffer, 0, num);
        strFile.append(current);
        buffer = new char[512];
    }
    reader.close();
    return strFile.toString();
}

【讨论】:

  • 也许已经晚了,但对其他人有用; Apache TIKA 可用于从不同的文件类型中提取元数据和文本,尤其是在您的情况下是文本文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多