List of usage examples for java.io PrintWriter PrintWriter
public PrintWriter(File file) throws FileNotFoundException
From source file:je3.rmi.MudClient.java
/** * The main program. It expects two or three arguments: * 0) the name of the host on which the mud server is running * 1) the name of the MUD on that host * 2) the name of a place within that MUD to start at (optional). * * It uses the Naming.lookup() method to obtain a RemoteMudServer object * for the named MUD on the specified host. Then it uses the getEntrance() * or getNamedPlace() method of RemoteMudServer to obtain the starting * RemoteMudPlace object. It prompts the user for a their name and * description, and creates a MudPerson object. Finally, it passes * the person and the place to runMud() to begin interaction with the MUD. **///from w w w . ja va 2 s . c om public static void main(String[] args) { try { String hostname = args[0]; // Each MUD is uniquely identified by a String mudname = args[1]; // host and a MUD name. String placename = null; // Each place in a MUD has a unique name if (args.length > 2) placename = args[2]; // Look up the RemoteMudServer object for the named MUD using // the default registry on the specified host. Note the use of // the Mud.mudPrefix constant to help prevent naming conflicts // in the registry. RemoteMudServer server = (RemoteMudServer)Naming.lookup("rmi://" + hostname + "/" + Mud.mudPrefix + mudname); // If the user did not specify a place in the mud, use // getEntrance() to get the initial place. Otherwise, call // getNamedPlace() to find the initial place. RemoteMudPlace location = null; if (placename == null) location = server.getEntrance(); else location = (RemoteMudPlace) server.getNamedPlace(placename); // Greet the user and ask for their name and description. // This relies on getLine() and getMultiLine() defined below. System.out.println("Welcome to " + mudname); String name = getLine("Enter your name: "); String description = getMultiLine("Please describe what " + "people see when they look at you:"); // Define an output stream that the MudPerson object will use to // display messages sent to it to the user. We'll use the console. PrintWriter myout = new PrintWriter(System.out); // Create a MudPerson object to represent the user in the MUD. // Use the specified name and description, and the output stream. MudPerson me = new MudPerson(name, description, myout); // Lower this thread's priority one notch so that broadcast // messages can appear even when we're blocking for I/O. This is // necessary on the Linux platform, but may not be necessary on all // platforms. int pri = Thread.currentThread().getPriority(); Thread.currentThread().setPriority(pri-1); // Finally, put the MudPerson into the RemoteMudPlace, and start // prompting the user for commands. runMud(location, me); } // If anything goes wrong, print a message and exit. catch (Exception e) { System.out.println(e); System.out.println("Usage: java MudClient <host> <mud> [<place>]"); System.exit(1); } }
From source file:ctrus.pa.bow.en.EnBagOfWords.java
public static void main(String[] args) throws Exception { // Parse the command line input BOWOptions opts = EnBOWOptions.getInstance(); opts.parseCLI(args);// w w w . j a v a 2 s .c om if (opts.hasOption(DefaultOptions.PRINT_HELP)) { opts.printHelp("HELP", new PrintWriter(System.out)); } else { EnBagOfWords eBow = new EnBagOfWords(); eBow.setup(opts); eBow.create(); eBow.printVocabulary(); } }
From source file:PopClean.java
public static void main(String args[]) { try {// w w w . ja v a 2 s .co m String hostname = null, username = null, password = null; int port = 110; int sizelimit = -1; String subjectPattern = null; Pattern pattern = null; Matcher matcher = null; boolean delete = false; boolean confirm = true; // Handle command-line arguments for (int i = 0; i < args.length; i++) { if (args[i].equals("-user")) username = args[++i]; else if (args[i].equals("-pass")) password = args[++i]; else if (args[i].equals("-host")) hostname = args[++i]; else if (args[i].equals("-port")) port = Integer.parseInt(args[++i]); else if (args[i].equals("-size")) sizelimit = Integer.parseInt(args[++i]); else if (args[i].equals("-subject")) subjectPattern = args[++i]; else if (args[i].equals("-debug")) debug = true; else if (args[i].equals("-delete")) delete = true; else if (args[i].equals("-force")) // don't confirm confirm = false; } // Verify them if (hostname == null || username == null || password == null || sizelimit == -1) usage(); // Make sure the pattern is a valid regexp if (subjectPattern != null) { pattern = Pattern.compile(subjectPattern); matcher = pattern.matcher(""); } // Say what we are going to do System.out .println("Connecting to " + hostname + " on port " + port + " with username " + username + "."); if (delete) { System.out.println("Will delete all messages longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } else { System.out.println("Will list subject lines for messages " + "longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } // If asked to delete, ask for confirmation unless -force is given if (delete && confirm) { System.out.println(); System.out.print("Do you want to proceed (y/n) [n]: "); System.out.flush(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); String response = console.readLine(); if (!response.equals("y")) { System.out.println("No messages deleted."); System.exit(0); } } // Connect to the server, and set up streams s = new Socket(hostname, port); in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); // Read the welcome message from the server, confirming it is OK. System.out.println("Connected: " + checkResponse()); // Now log in send("USER " + username); // Send username, wait for response send("PASS " + password); // Send password, wait for response System.out.println("Logged in"); // Check how many messages are waiting, and report it String stat = send("STAT"); StringTokenizer t = new StringTokenizer(stat); System.out.println(t.nextToken() + " messages in mailbox."); System.out.println("Total size: " + t.nextToken()); // Get a list of message numbers and sizes send("LIST"); // Send LIST command, wait for OK response. // Now read lines from the server until we get . by itself List msgs = new ArrayList(); String line; for (;;) { line = in.readLine(); if (line == null) throw new IOException("Unexpected EOF"); if (line.equals(".")) break; msgs.add(line); } // Now loop through the lines we read one at a time. // Each line should specify the message number and its size. int nummsgs = msgs.size(); for (int i = 0; i < nummsgs; i++) { String m = (String) msgs.get(i); StringTokenizer st = new StringTokenizer(m); int msgnum = Integer.parseInt(st.nextToken()); int msgsize = Integer.parseInt(st.nextToken()); // If the message is too small, ignore it. if (msgsize <= sizelimit) continue; // If we're listing messages, or matching subject lines // find the subject line for this message String subject = null; if (!delete || pattern != null) { subject = getSubject(msgnum); // get the subject line // If we couldn't find a subject, skip the message if (subject == null) continue; // If this subject does not match the pattern, then // skip the message if (pattern != null) { matcher.reset(subject); if (!matcher.matches()) continue; } // If we are listing, list this message if (!delete) { System.out.println("Subject " + msgnum + ": " + subject); continue; // so we never delete it } } // If we were asked to delete, then delete the message if (delete) { send("DELE " + msgnum); if (pattern == null) System.out.println("Deleted message " + msgnum); else System.out.println("Deleted message " + msgnum + ": " + subject); } } // When we're done, log out and shutdown the connection shutdown(); } catch (Exception e) { // If anything goes wrong print exception and show usage System.err.println(e); usage(); // Always try to shutdown nicely so the server doesn't hang on us shutdown(); } }
From source file:com.jaeksoft.searchlib.util.StringUtils.java
public static void main(String[] args) throws IOException { List<String> lines = FileUtils.readLines(new File(args[0])); FileWriter fw = new FileWriter(new File(args[1])); PrintWriter pw = new PrintWriter(fw); for (String line : lines) pw.println(StringEscapeUtils.unescapeHtml(line)); pw.close();//w ww. j av a 2 s. c o m fw.close(); }
From source file:edu.msu.cme.rdp.multicompare.Main.java
public static void main(String[] args) throws Exception { PrintStream hier_out = null;//from w w w . j av a2 s . c om PrintWriter assign_out = new PrintWriter(new NullWriter()); PrintStream bootstrap_out = null; File hier_out_filename = null; String propFile = null; File biomFile = null; File metadataFile = null; PrintWriter shortseq_out = null; List<MCSample> samples = new ArrayList(); ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; float conf = CmdOptions.DEFAULT_CONF; String gene = null; int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } else { throw new IllegalArgumentException("Require the output file for classification assignment"); } if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT)); hier_out = new PrintStream(hier_out_filename); } if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) { biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) { metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT)); } if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) { if (gene != null) { throw new IllegalArgumentException( "Already specified the gene from the default location. Can not specify train_propfile"); } else { propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) { String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT); if (f.equalsIgnoreCase("allrank")) { format = ClassificationResultFormatter.FORMAT.allRank; } else if (f.equalsIgnoreCase("fixrank")) { format = ClassificationResultFormatter.FORMAT.fixRank; } else if (f.equalsIgnoreCase("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("biom")) { format = ClassificationResultFormatter.FORMAT.biom; } else { throw new IllegalArgumentException( "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (propFile != null) { throw new IllegalArgumentException( "Already specified train_propfile. Can not specify gene any more"); } gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase(); if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) { throw new IllegalArgumentException(gene + " not found, choose from" + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + ", " + ClassifierFactory.FUNGALITS_unite_GENE); } } if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) { min_bootstrap_words = Integer .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)); if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS); } } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT); try { conf = Float.valueOf(confString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Confidence must be a decimal number"); } if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) { shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) { bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)); } if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) { throw new IllegalArgumentException("biom format requires an input biom file"); } if (biomFile != null) { // if input biom file provided, use biom format format = ClassificationResultFormatter.FORMAT.biom; } args = line.getArgs(); for (String arg : args) { String[] inFileNames = arg.split(","); File inputFile = new File(inFileNames[0]); File idmappingFile = null; if (!inputFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\""); } if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\""); } } MCSample nextSample = new MCSample(inputFile, idmappingFile); samples.add(nextSample); } if (propFile == null && gene == null) { gene = CmdOptions.DEFAULT_GENE; } if (samples.size() < 1) { throw new IllegalArgumentException("Require at least one sample files"); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, ""); return; } MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile); MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format, min_bootstrap_words); assign_out.close(); if (hier_out != null) { DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples); result.getRoot().topDownVisit(printVisitor); hier_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(hier_out_filename.getParentFile(), "cnadjusted_" + hier_out_filename.getName()); PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s); printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true); result.getRoot().topDownVisit(printVisitor); cn_corrected_hier_out.close(); } } if (bootstrap_out != null) { for (MCSample sample : samples) { MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample); } bootstrap_out.close(); } if (shortseq_out != null) { for (String id : result.getBadSequences()) { shortseq_out.write(id + "\n"); } shortseq_out.close(); } }
From source file:com.joliciel.jochre.search.JochreSearch.java
/** * @param args//from w w w. j a va 2 s. c o m */ public static void main(String[] args) { try { Map<String, String> argMap = new HashMap<String, String>(); for (String arg : args) { int equalsPos = arg.indexOf('='); String argName = arg.substring(0, equalsPos); String argValue = arg.substring(equalsPos + 1); argMap.put(argName, argValue); } String command = argMap.get("command"); argMap.remove("command"); String logConfigPath = argMap.get("logConfigFile"); if (logConfigPath != null) { argMap.remove("logConfigFile"); Properties props = new Properties(); props.load(new FileInputStream(logConfigPath)); PropertyConfigurator.configure(props); } LOG.debug("##### Arguments:"); for (Entry<String, String> arg : argMap.entrySet()) { LOG.debug(arg.getKey() + ": " + arg.getValue()); } SearchServiceLocator locator = SearchServiceLocator.getInstance(); SearchService searchService = locator.getSearchService(); if (command.equals("buildIndex")) { String indexDirPath = argMap.get("indexDir"); String documentDirPath = argMap.get("documentDir"); File indexDir = new File(indexDirPath); indexDir.mkdirs(); File documentDir = new File(documentDirPath); JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir); builder.updateDocument(documentDir); } else if (command.equals("updateIndex")) { String indexDirPath = argMap.get("indexDir"); String documentDirPath = argMap.get("documentDir"); boolean forceUpdate = false; if (argMap.containsKey("forceUpdate")) { forceUpdate = argMap.get("forceUpdate").equals("true"); } File indexDir = new File(indexDirPath); indexDir.mkdirs(); File documentDir = new File(documentDirPath); JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir); builder.updateIndex(documentDir, forceUpdate); } else if (command.equals("search")) { HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator.getInstance(locator); HighlightService highlightService = highlightServiceLocator.getHighlightService(); String indexDirPath = argMap.get("indexDir"); File indexDir = new File(indexDirPath); JochreQuery query = searchService.getJochreQuery(argMap); JochreIndexSearcher searcher = searchService.getJochreIndexSearcher(indexDir); TopDocs topDocs = searcher.search(query); Set<Integer> docIds = new LinkedHashSet<Integer>(); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { docIds.add(scoreDoc.doc); } Set<String> fields = new HashSet<String>(); fields.add("text"); Highlighter highlighter = highlightService.getHighlighter(query, searcher.getIndexSearcher()); HighlightManager highlightManager = highlightService .getHighlightManager(searcher.getIndexSearcher()); highlightManager.setDecimalPlaces(query.getDecimalPlaces()); highlightManager.setMinWeight(0.0); highlightManager.setIncludeText(true); highlightManager.setIncludeGraphics(true); Writer out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8)); if (command.equals("highlight")) { highlightManager.highlight(highlighter, docIds, fields, out); } else { highlightManager.findSnippets(highlighter, docIds, fields, out); } } else { throw new RuntimeException("Unknown command: " + command); } } catch (RuntimeException e) { LogUtils.logError(LOG, e); throw e; } catch (IOException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } }
From source file:org.jfree.chart.demo.ImageMapDemo4.java
/** * Starting point for the demo.//from ww w. ja va 2 s . co m * * @param args ignored. */ public static void main(final String[] args) { // create a chart final double[][] data = new double[][] { { 56.0, -12.0, 34.0, 76.0, 56.0, 100.0, 67.0, 45.0 }, { 37.0, 45.0, 67.0, 25.0, 34.0, 34.0, 100.0, 53.0 }, { 43.0, 54.0, 34.0, 34.0, 87.0, 64.0, 73.0, 12.0 } }; final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Series ", "Type ", data); JFreeChart chart = null; final boolean drilldown = true; if (drilldown) { final CategoryAxis3D categoryAxis = new CategoryAxis3D("Category"); final ValueAxis valueAxis = new NumberAxis3D("Value"); final BarRenderer3D renderer = new BarRenderer3D(); renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator()); renderer.setItemURLGenerator(new StandardCategoryURLGenerator("bar_chart_detail.jsp")); final CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer); plot.setOrientation(PlotOrientation.VERTICAL); chart = new JFreeChart("Bar Chart", JFreeChart.DEFAULT_TITLE_FONT, plot, true); } else { chart = ChartFactory.createBarChart3D("Bar Chart", // chart title "Category", // domain axis label "Value", // range axis label dataset, // data PlotOrientation.VERTICAL, true, // include legend true, false); } chart.setBackgroundPaint(java.awt.Color.white); // **************************************************************************** // * JFREECHART DEVELOPER GUIDE * // * The JFreeChart Developer Guide, written by David Gilbert, is available * // * to purchase from Object Refinery Limited: * // * * // * http://www.object-refinery.com/jfreechart/guide.html * // * * // * Sales are used to provide funding for the JFreeChart project - please * // * support us so that we can continue developing free software. * // **************************************************************************** // save it to an image try { final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); final File file1 = new File("barchart101.png"); ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info); // write an HTML page incorporating the image with an image map final File file2 = new File("barchart101.html"); final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); final PrintWriter writer = new PrintWriter(out); writer.println("<HTML>"); writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>"); writer.println("<BODY>"); // ChartUtilities.writeImageMap(writer, "chart", info); writer.println("<IMG SRC=\"barchart100.png\" " + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">"); writer.println("</BODY>"); writer.println("</HTML>"); writer.close(); } catch (IOException e) { System.out.println(e.toString()); } }
From source file:OpenCalaisGenerateRdfPropertiesFromWebPages.java
public static void main(String[] args) throws Exception { new OpenCalaisGenerateRdfPropertiesFromWebPages("testdata/websites.txt", new PrintWriter("tempdata/gen_rdf.nt")); }
From source file:org.jfree.chart.demo.ImageMapDemo1.java
/** * Starting point for the demo./*ww w . ja v a 2s. c om*/ * * @param args ignored. */ public static void main(final String[] args) { // create a chart final double[][] data = new double[][] { { 56.0, -12.0, 34.0, 76.0, 56.0, 100.0, 67.0, 45.0 }, { 37.0, 45.0, 67.0, 25.0, 34.0, 34.0, 100.0, 53.0 }, { 43.0, 54.0, 34.0, 34.0, 87.0, 64.0, 73.0, 12.0 } }; final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Series ", "Type ", data); JFreeChart chart = null; final boolean drilldown = true; if (drilldown) { final CategoryAxis categoryAxis = new CategoryAxis("Category"); final ValueAxis valueAxis = new NumberAxis("Value"); final BarRenderer renderer = new BarRenderer(); renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator()); renderer.setItemURLGenerator(new StandardCategoryURLGenerator("bar_chart_detail.jsp")); final CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer); plot.setOrientation(PlotOrientation.VERTICAL); chart = new JFreeChart("Bar Chart", JFreeChart.DEFAULT_TITLE_FONT, plot, true); } else { chart = ChartFactory.createBarChart("Vertical Bar Chart", // chart title "Category", // domain axis label "Value", // range axis label dataset, // data PlotOrientation.VERTICAL, true, // include legend true, false); } chart.setBackgroundPaint(java.awt.Color.white); // **************************************************************************** // * JFREECHART DEVELOPER GUIDE * // * The JFreeChart Developer Guide, written by David Gilbert, is available * // * to purchase from Object Refinery Limited: * // * * // * http://www.object-refinery.com/jfreechart/guide.html * // * * // * Sales are used to provide funding for the JFreeChart project - please * // * support us so that we can continue developing free software. * // **************************************************************************** // save it to an image try { final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); final File file1 = new File("barchart100.png"); ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info); // write an HTML page incorporating the image with an image map final File file2 = new File("barchart100.html"); final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); final PrintWriter writer = new PrintWriter(out); writer.println("<HTML>"); writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>"); writer.println("<BODY>"); // ChartUtilities.writeImageMap(writer, "chart", info); writer.println("<IMG SRC=\"barchart100.png\" " + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">"); writer.println("</BODY>"); writer.println("</HTML>"); writer.close(); } catch (IOException e) { System.out.println(e.toString()); } }
From source file:Anaphora_Resolution.ParseAllXMLDocuments.java
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerException { // File dataFolder = new File("DataToPort"); // File[] documents; String grammar = "grammar/englishPCFG.ser.gz"; String[] options = { "-maxLength", "100", "-retainTmpSubcategories" }; //LexicalizedParser lp = new LexicalizedParser(grammar, options); LexicalizedParser lp = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz"); ////from www. j av a 2 s . com // if (dataFolder.isDirectory()) { // documents = dataFolder.listFiles(); // } else { // documents = new File[] {dataFolder}; // } // int currfile = 0; // int totfiles = documents.length; // for (File paper : documents) { // currfile++; // if (paper.getName().equals(".DS_Store")||paper.getName().equals(".xml")) { // currfile--; // totfiles--; // continue; // } // System.out.println("Working on "+paper.getName()+" (file "+currfile+" out of "+totfiles+")."); // // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); // This is for XML // DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Document doc = docBuilder.parse(paper.getAbsolutePath()); // // NodeList textlist = doc.getElementsByTagName("text"); // for(int i=0; i < textlist.getLength(); i++) { // Node currentnode = textlist.item(i); // String wholetext = textlist.item(i).getTextContent(); String wholetext = "How about other changes for example the ways of doing the work and \n" + "\n" + "Iwould say security has , there 's more pressure put on people now than there used to be because obviously , especially after Locherbie , they tightened up on security and there 's a lot more pressure now especially from the ETR and stuff like that \n" + "People do n't feel valued any more , they feel I do n't know I think they feel that nobody cares about them really anyway \n"; //System.out.println(wholetext); //Iterable<List<? extends HasWord>> sentences; ArrayList<Tree> parseTrees = new ArrayList<Tree>(); String asd = ""; int j = 0; StringReader stringreader = new StringReader(wholetext); DocumentPreprocessor dp = new DocumentPreprocessor(stringreader); @SuppressWarnings("rawtypes") ArrayList<List> sentences = preprocess(dp); for (List sentence : sentences) { parseTrees.add(lp.apply(sentence)); // Parsing a new sentence and adding it to the parsed tree ArrayList<Tree> PronounsList = findPronouns(parseTrees.get(j)); // Locating all pronouns to resolve in the sentence Tree corefedTree; for (Tree pronounTree : PronounsList) { parseTrees.set(parseTrees.size() - 1, HobbsResolve(pronounTree, parseTrees)); // Resolving the coref and modifying the tree for each pronoun } StringWriter strwr = new StringWriter(); PrintWriter prwr = new PrintWriter(strwr); TreePrint tp = new TreePrint("penn"); tp.printTree(parseTrees.get(j), prwr); prwr.flush(); asd += strwr.toString(); j++; } String armando = ""; for (Tree sentence : parseTrees) { for (Tree leaf : Trees.leaves(sentence)) armando += leaf + " "; } System.out.println(wholetext); System.out.println(); System.out.println("......"); System.out.println(armando); System.out.println("All done."); // currentnode.setTextContent(asd); // } // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(doc); // StreamResult result = new StreamResult(paper); // transformer.transform(source, result); // // System.out.println("Done"); // } }