我是否知道如何将输出写入文本文件,与show()函数显示的输出相同。例如,当我执行此代码时:
p.show();
输出:
(TOP (S (NP (PRP$ My) (NN name)) (VP (VBZ is) (NP (NNP David.))))
当我执行此代码时:
System.out.println(p.toString());
输出:
My name is David.
因此,当我尝试使用以下代码将此输出写入文本文件时:
fout.write((p.toString()+newline).getBytes());
文本文件中的输出与“System.out.println(p.toString());”显示的输出相同。“。
那么,如何将show()函数所示的相同输出写入文本文件?
完整代码:
package com.mycompany.app;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
public class ChunkParser {
public static void main(String[] args) throws IOException {
InputStream modelIn = new FileInputStream("D:/NetBeansProjects/my-app/src/main/resources/en-parser-chunking.zip");
FileInputStream fin=new FileInputStream("D:/NetBeansProjects/my-app/textfile.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine=br.readLine();
System.out.println("Full Text: "+"\n"+strLine+"\n");
try {
ParserModel pmodel = new ParserModel(modelIn);
Parser parserc = ParserFactory.create(pmodel);
Parse topParses[] = ParserTool.parseLine(strLine, parserc, 1);
FileOutputStream fout=new FileOutputStream("D:/NetBeansProjects/my-app/ChunkParser.txt");
String newline = System.getProperty("line.separator");
for (Parse p : topParses){
p.show();
System.out.println(p.toString());
fout.write((p.toString()+newline).getBytes());
}
fout.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (modelIn != null) {
try {
modelIn.close();
}
catch (IOException e) {
}
}
fin.close();
}
}
}
答案 0 :(得分:1)
使用p.show(sb)而不是调用p.show(),其中sb是StringBuffer。然后,您可以从StringBuffer中获取文本。下次详细了解opennlp的文档。