1

下面是我在 java 中使用 stanford nlp 获取单个文本文件的解析树和依赖项的程序

public class Stanford {

public static void demoDP(LexicalizedParser lp, String filename) throws IOException {

    //FileOutputStream fos = new FileOutputStream("C://perl_java//Text-Parsed.txt");
      //ObjectOutputStream oos = new ObjectOutputStream(fos);

    //BufferedWriter bwriter = new BufferedWriter(fwriter);
    TreebankLanguagePack tlp = new PennTreebankLanguagePack();
    System.out.println("in method");
    System.out.println("lp in method"+lp);
    GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
    System.out.println(filename);
    for (List<HasWord> sentence : new DocumentPreprocessor(filename)) {
      Tree parse = lp.apply(sentence);
      parse.pennPrint();
      System.out.println();
      System.out.println("hiiiiii");
      GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
      Collection tdl = gs.typedDependenciesCCprocessed();
      System.out.println(tdl);
      PrintWriter pw = new PrintWriter("C://perl_java//Text-Parsed.txt");
      pw.print(tdl);
      pw.close();
       //oos.write(tdl.toString());
      //bwriter.write(tdl);
      System.out.println();
    }
    //oos.close();
  }


 public static void main(String args[])
 {
 LexicalizedParser lp =       LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz");
demoDP(lp,"C://sample.txt")
 }
}

我在控制台中得到输出

我怎么能把它写到我用过的文本文件中bufferwriterfileoutputstream但没有写进去,有人能建议我怎么做吗

谢谢

4

2 回答 2

1

试试这个代码:

 File f=new File("Data/tree.txt");
      PrintWriter pw=new PrintWriter(f);
    // This option shows loading and using an explicit tokenizer
    String sent2 = "This is another sentence.";
    TokenizerFactory<CoreLabel> tokenizerFactory =PTBTokenizer.factory(new CoreLabelTokenFactory(), "");
    Tokenizer<CoreLabel> tok =tokenizerFactory.getTokenizer(new StringReader(sent2));
    List<CoreLabel> rawWords2 = tok.tokenize();
   Tree parse = lp.apply(rawWords2);

    TreebankLanguagePack tlp = new PennTreebankLanguagePack();
    GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
    GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
    List<TypedDependency> tdl = gs.typedDependenciesCCprocessed();
  System.out.println(tdl);
    System.out.println();
    // You can also use a TreePrint object to print trees and dependencies
    TreePrint tp = new TreePrint("penn,typedDependenciesCollapsed");
    tp.printTree(parse,pw);
于 2014-03-12T07:28:55.170 回答
0

FileOutputStream 或类似的东西应该在 for 循环之前进行构造,在 for 循环中写入并在 for 循环之后关闭。在上面的示例中,您将在 for 循环中关闭 PrintWriter。

于 2013-08-22T08:57:47.320 回答