public static void Main(string[] args) { string inputDicts = "/u/nlp/data/chinese-dictionaries/plain/ne_wikipedia-utf8.txt,/u/nlp/data/chinese-dictionaries/plain/newsexplorer_entities_utf8.txt,/u/nlp/data/chinese-dictionaries/plain/Ch-name-list-utf8.txt,/u/nlp/data/chinese-dictionaries/plain/wikilex-20070908-zh-en.txt,/u/nlp/data/chinese-dictionaries/plain/adso-1.25-050405-monolingual-clean.utf8.txt,/u/nlp/data/chinese-dictionaries/plain/lexicon_108k_normalized.txt,/u/nlp/data/chinese-dictionaries/plain/lexicon_mandarintools_normalized.txt,/u/nlp/data/chinese-dictionaries/plain/harbin-ChineseNames_utf8.txt,/u/nlp/data/chinese-dictionaries/plain/lexicon_HowNet_normalized.txt"; string output = "/u/nlp/data/gale/segtool/stanford-seg/classifiers/dict-chris6.ser.gz"; IDictionary <string, int> flagMap = Generics.NewHashMap(); flagMap["-inputDicts"] = 1; flagMap["-output"] = 1; IDictionary <string, string[]> argsMap = StringUtils.ArgsToMap(args, flagMap); // args = argsMap.get(null); if (argsMap.Keys.Contains("-inputDicts")) { inputDicts = argsMap["-inputDicts"][0]; } if (argsMap.Keys.Contains("-output")) { output = argsMap["-output"][0]; } string[] dicts = inputDicts.Split(","); ChineseDocumentToSentenceProcessor cdtos = new ChineseDocumentToSentenceProcessor(null); bool expandMidDot = true; Edu.Stanford.Nlp.Wordseg.ChineseDictionary dict = new Edu.Stanford.Nlp.Wordseg.ChineseDictionary(dicts, cdtos, expandMidDot); dict.SerializeDictionary(output); }
private static bool ValidateCommandLine(string[] args) { IDictionary <string, string[]> argsMap = StringUtils.ArgsToMap(args, optionArgDefs); foreach (KeyValuePair <string, string[]> opt in argsMap) { string key = opt.Key; if (key == null) { } else { switch (key) { case "-d": { // continue; MakeDistrib = true; distribName = opt.Value[0]; break; } case "-v": { Verbose = true; break; } case "-p": { outputPath = opt.Value[0]; break; } default: { return(false); } } } } //Regular arguments string[] rest = argsMap[null]; if (rest == null || rest.Length != MinArgs) { return(false); } else { configFile = rest[0]; } return(true); }
private static bool ValidateCommandLine(string[] args) { IDictionary <string, string[]> argsMap = StringUtils.ArgsToMap(args, optionArgDefs); foreach (KeyValuePair <string, string[]> opt in argsMap) { string key = opt.Key; if (key != null) { switch (key) { case "-y": { MaxGoldYield = System.Convert.ToInt32(opt.Value[0]); break; } case "-l": { Language = Language.ValueOf(opt.Value[0]); break; } case "-v": { Verbose = true; break; } default: { return(false); } } } } //Regular arguments string[] rest = argsMap[null]; if (rest == null || rest.Length != MinArgs) { return(false); } else { goldFile = new File(rest[0]); guessFile = new File(rest[1]); } return(true); }
// = false; // not an instantiable class /// <summary>Usage: java edu.stanford.nlp.trees.tregex.tsurgeon.Tsurgeon [-s] -treeFile file-with-trees [-po matching-pattern operation] operation-file-1 operation-file-2 ...</summary> /// <remarks> /// Usage: java edu.stanford.nlp.trees.tregex.tsurgeon.Tsurgeon [-s] -treeFile file-with-trees [-po matching-pattern operation] operation-file-1 operation-file-2 ... operation-file-n /// <h4>Arguments:</h4> /// Each argument should be the name of a transformation file that contains a list of pattern /// and transformation operation list pairs. That is, it is a sequence of pairs of a /// <see cref="Edu.Stanford.Nlp.Trees.Tregex.TregexPattern"/> /// pattern on one or more lines, then a /// blank line (empty or whitespace), then a list of transformation operations one per line /// (as specified by <b>Legal operation syntax</b> below) to apply when the pattern is matched, /// and then another blank line (empty or whitespace). /// Note the need for blank lines: The code crashes if they are not present as separators /// (although the blank line at the end of the file can be omitted). /// The script file can include comment lines, either whole comment lines or /// trailing comments introduced by %, which extend to the end of line. A needed percent /// mark can be escaped by a preceding backslash. /// <p> /// For example, if you want to excise an SBARQ node whenever it is the parent of an SQ node, /// and relabel the SQ node to S, your transformation file would look like this: /// <blockquote> /// <code> /// SBARQ=n1 < SQ=n2<br /> /// <br /> /// excise n1 n1<br /> /// relabel n2 S /// </code> /// </blockquote> /// <h4>Options:</h4> /// <ul> /// <li> /// <c>-treeFile <filename></c> /// specify the name of the file that has the trees you want to transform. /// <li> /// <c>-po <matchPattern> <operation></c> /// Apply a single operation to every tree using the specified match pattern and the specified operation. Use this option /// when you want to quickly try the effect of one pattern/surgery combination, and are too lazy to write a transformation file. /// <li> /// <c>-s</c> /// Print each output tree on one line (default is pretty-printing). /// <li> /// <c>-m</c> /// For every tree that had a matching pattern, print "before" (prepended as "Operated on:") and "after" (prepended as "Result:"). Unoperated on trees just pass through the transducer as usual. /// <li> /// <c>-encoding X</c> /// Uses character set X for input and output of trees. /// <li> /// <c>-macros <filename></c> /// A file of macros to use on the tregex pattern. Macros should be one per line, with original and replacement separated by tabs. /// <li> /// <c>-hf <headFinder-class-name></c> /// use the specified /// <see cref="Edu.Stanford.Nlp.Trees.IHeadFinder"/> /// class to determine headship relations. /// <li> /// <c>-hfArg <string></c> /// pass a string argument in to the /// <see cref="Edu.Stanford.Nlp.Trees.IHeadFinder"/> /// class's constructor. /// <c>-hfArg</c> /// can be used multiple times to pass in multiple arguments. /// <li> /// <c>-trf <TreeReaderFactory-class-name></c> /// use the specified /// <see cref="Edu.Stanford.Nlp.Trees.ITreeReaderFactory"/> /// class to read trees from files. /// </ul> /// <h4>Legal operation syntax:</h4> /// <ul> /// <li> /// <c>delete <name></c> /// deletes the node and everything below it. /// <li> /// <c>prune <name></c> /// Like delete, but if, after the pruning, the parent has no children anymore, the parent is pruned too. Pruning continues to affect all ancestors until one is found with remaining children. This may result in a null tree. /// <li> /// <c>excise <name1> <name2></c> /// The name1 node should either dominate or be the same as the name2 node. This excises out everything from /// name1 to name2. All the children of name2 go into the parent of name1, where name1 was. /// <li> /// <c>relabel <name> <new-label></c> /// Relabels the node to have the new label. <br /> /// There are three possible forms: <br /> /// <c>relabel nodeX VP</c> /// - for changing a node label to an /// alphanumeric string <br /> /// <c>relabel nodeX /''/</c> /// - for relabeling a node to /// something that isn't a valid identifier without quoting <br /> /// <c>relabel nodeX /^VB(.*)$/verb\\/$1/</c> /// - for regular /// expression based relabeling. In this case, all matches of the /// regular expression against the node label are replaced with the /// replacement String. This has the semantics of Java/Perl's /// replaceAll: you may use capturing groups and put them in /// replacements with $n. For example, if the pattern is /foo/bar/ /// and the node matched is "foo", the replaceAll semantics result in /// "barbar". If the pattern is /^foo(.*)$/bar$1/ and node matched is /// "foofoo", relabel will result in "barfoo". <br /> /// When using the regex replacement method, you can also use the /// sequences ={node} and %{var} in the replacement string to use /// captured nodes or variable strings in the replacement string. /// For example, if the Tregex pattern was "duck=bar" and the relabel /// is /foo/={bar}/, "foofoo" will be replaced with "duckduck". <br /> /// To concatenate two nodes named in the tregex pattern, for /// example, you can use the pattern /^.*$/={foo}={bar}/. Note that /// the ^.*$ is necessary to make sure the regex pattern only matches /// and replaces once on the entire node name. <br /> /// To get an "=" or a "%" in the replacement, using \ escaping. /// Also, as in the example you can escape a slash in the middle of /// the second and third forms with \\/ and \\\\. <br /> /// <li> /// <c>insert <name> <position></c> /// or /// <c>insert <tree> <position></c> /// inserts the named node or tree into the position specified. /// <li> /// <c>move <name> <position></c> /// moves the named node into the specified position. /// <p>Right now the only ways to specify position are: /// <p> /// <c>$+ <name></c> /// the left sister of the named node<br /> /// <c>$- <name></c> /// the right sister of the named node<br /> /// <c>>i <name></c> /// the i_th daughter of the named node<br /> /// <c>>-i <name></c> /// the i_th daughter, counting from the right, of the named node. /// <li> /// <c>replace <name1> <name2></c> /// deletes name1 and inserts a copy of name2 in its place. /// <li> /// <c>replace <name> <tree> <tree2>...</c> /// deletes name and inserts the new tree(s) in its place. If /// more than one replacement tree is given, each of the new /// subtrees will be added in order where the old tree was. /// Multiple subtrees at the root is an illegal operation and /// will throw an exception. /// <li> /// <c>createSubtree <auxiliary-tree-or-label> <name1> [<name2>]</c> /// Create a subtree out of all the nodes from /// <c><name1></c> /// through /// <c><name2></c> /// . The subtree is moved to the foot of the given /// auxiliary tree, and the tree is inserted where the nodes of /// the subtree used to reside. If a simple label is provided as /// the first argument, the subtree is given a single parent with /// a name corresponding to the label. To limit the operation to /// just one node, elide /// <c><name2></c> /// . /// <li> /// <c>adjoin <auxiliary_tree> <name></c> /// Adjoins the specified auxiliary tree into the named node. /// The daughters of the target node will become the daughters of the foot of the auxiliary tree. /// <li> /// <c>adjoinH <auxiliary_tree> <name></c> /// Similar to adjoin, but preserves the target node /// and makes it the root of /// <c><tree></c> /// . (It is still accessible as /// <c>name</c> /// . The root of the /// auxiliary tree is ignored.) /// <li> /// <c>adjoinF <auxiliary_tree> <name></c> /// Similar to adjoin, /// but preserves the target node and makes it the foot of /// <c><tree></c> /// . /// (It is still accessible as /// <c>name</c> /// , and retains its status as parent of its children. /// The root of the auxiliary tree is ignored.) /// <li> <dt> /// <c>coindex <name1> <name2> ... <nameM></c> /// Puts a (Penn Treebank style) /// coindexation suffix of the form "-N" on each of nodes name_1 through name_m. The value of N will be /// automatically generated in reference to the existing coindexations in the tree, so that there is never /// an accidental clash of indices across things that are not meant to be coindexed. /// </ul> /// <p> /// In the context of /// <c>adjoin</c> /// , /// <c>adjoinH</c> /// , /// <c>adjoinF</c> /// , and /// <c>createSubtree</c> /// , an auxiliary /// tree is a tree in Penn Treebank format with /// <c>@</c> /// on /// exactly one of the leaves denoting the foot of the tree. /// The operations which use the foot use the labeled node. /// For example: /// </p> /// <blockquote> /// Tsurgeon: /// <c>adjoin (FOO (BAR@)) foo</c> /// <br /> /// Tregex: /// <c>B=foo</c> /// <br /> /// Input: /// <c>(A (B 1 2))</c> /// Output: /// <c>(A (FOO (BAR 1 2)))</c> /// </blockquote> /// <p> /// Tsurgeon applies the same operation to the same tree for as long /// as the given tregex operation matches. This means that infinite /// loops are very easy to cause. One common situation where this comes up /// is with an insert operation will repeats infinitely many times /// unless you add an expression to the tregex that matches against /// the inserted pattern. For example, this pattern will infinite loop: /// </p> /// <blockquote> /// <code> /// TregexPattern tregex = TregexPattern.compile("S=node << NP"); <br /> /// TsurgeonPattern tsurgeon = Tsurgeon.parseOperation("insert (NP foo) >-1 node"); /// </code> /// </blockquote> /// <p> /// This pattern, though, will terminate: /// </p> /// <blockquote> /// <code> /// TregexPattern tregex = TregexPattern.compile("S=node << NP !<< foo"); <br /> /// TsurgeonPattern tsurgeon = Tsurgeon.parseOperation("insert (NP foo) >-1 node"); /// </code> /// </blockquote> /// <p> /// Tsurgeon has (very) limited support for conditional statements. /// If a pattern is prefaced with /// <c>if exists <name></c> /// , /// the rest of the pattern will only execute if /// the named node was found in the corresponding TregexMatcher. /// </p> /// </remarks> /// <param name="args"> /// a list of names of files each of which contains a single tregex matching pattern plus a list, one per line, /// of transformation operations to apply to the matched pattern. /// </param> /// <exception cref="System.Exception">If an I/O or pattern syntax error</exception> public static void Main(string[] args) { string headFinderClassName = null; string headFinderOption = "-hf"; string[] headFinderArgs = null; string headFinderArgOption = "-hfArg"; string encoding = "UTF-8"; string encodingOption = "-encoding"; if (args.Length == 0) { log.Info("Usage: java edu.stanford.nlp.trees.tregex.tsurgeon.Tsurgeon [-s] -treeFile <file-with-trees> [-po <matching-pattern> <operation>] <operation-file-1> <operation-file-2> ... <operation-file-n>"); System.Environment.Exit(0); } string treePrintFormats; string singleLineOption = "-s"; string verboseOption = "-v"; string matchedOption = "-m"; // if set, then print original form of trees that are matched & thus operated on string patternOperationOption = "-po"; string treeFileOption = "-treeFile"; string trfOption = "-trf"; string macroOption = "-macros"; string macroFilename = string.Empty; IDictionary <string, int> flagMap = Generics.NewHashMap(); flagMap[patternOperationOption] = 2; flagMap[treeFileOption] = 1; flagMap[trfOption] = 1; flagMap[singleLineOption] = 0; flagMap[encodingOption] = 1; flagMap[headFinderOption] = 1; flagMap[macroOption] = 1; IDictionary <string, string[]> argsMap = StringUtils.ArgsToMap(args, flagMap); args = argsMap[null]; if (argsMap.Contains(headFinderOption)) { headFinderClassName = argsMap[headFinderOption][0]; } if (argsMap.Contains(headFinderArgOption)) { headFinderArgs = argsMap[headFinderArgOption]; } if (argsMap.Contains(verboseOption)) { verbose = true; } if (argsMap.Contains(singleLineOption)) { treePrintFormats = "oneline,"; } else { treePrintFormats = "penn,"; } if (argsMap.Contains(encodingOption)) { encoding = argsMap[encodingOption][0]; } if (argsMap.Contains(macroOption)) { macroFilename = argsMap[macroOption][0]; } TreePrint tp = new TreePrint(treePrintFormats, new PennTreebankLanguagePack()); PrintWriter pwOut = new PrintWriter(new OutputStreamWriter(System.Console.Out, encoding), true); ITreeReaderFactory trf; if (argsMap.Contains(trfOption)) { string trfClass = argsMap[trfOption][0]; trf = ReflectionLoading.LoadByReflection(trfClass); } else { trf = new TregexPattern.TRegexTreeReaderFactory(); } Treebank trees = new DiskTreebank(trf, encoding); if (argsMap.Contains(treeFileOption)) { trees.LoadPath(argsMap[treeFileOption][0]); } if (trees.IsEmpty()) { log.Info("Warning: No trees specified to operate on. Use -treeFile path option."); } TregexPatternCompiler compiler; if (headFinderClassName == null) { compiler = new TregexPatternCompiler(); } else { IHeadFinder hf; if (headFinderArgs == null) { hf = ReflectionLoading.LoadByReflection(headFinderClassName); } else { hf = ReflectionLoading.LoadByReflection(headFinderClassName, (object[])headFinderArgs); } compiler = new TregexPatternCompiler(hf); } Macros.AddAllMacros(compiler, macroFilename, encoding); IList <Pair <TregexPattern, TsurgeonPattern> > ops = new List <Pair <TregexPattern, TsurgeonPattern> >(); if (argsMap.Contains(patternOperationOption)) { TregexPattern matchPattern = compiler.Compile(argsMap[patternOperationOption][0]); TsurgeonPattern p = ParseOperation(argsMap[patternOperationOption][1]); ops.Add(new Pair <TregexPattern, TsurgeonPattern>(matchPattern, p)); } else { foreach (string arg in args) { IList <Pair <TregexPattern, TsurgeonPattern> > pairs = GetOperationsFromFile(arg, encoding, compiler); foreach (Pair <TregexPattern, TsurgeonPattern> pair in pairs) { if (verbose) { log.Info(pair.Second()); } ops.Add(pair); } } } foreach (Tree t in trees) { Tree original = t.DeepCopy(); Tree result = ProcessPatternsOnTree(ops, t); if (argsMap.Contains(matchedOption) && matchedOnTree) { pwOut.Println("Operated on: "); DisplayTree(original, tp, pwOut); pwOut.Println("Result: "); } DisplayTree(result, tp, pwOut); } }
/// <exception cref="System.IO.IOException"/> public static void Main(string[] args) { IDictionary <string, int> flagsToNumArgs = Generics.NewHashMap(); flagsToNumArgs["-parser"] = int.Parse(3); flagsToNumArgs["-lex"] = int.Parse(3); flagsToNumArgs["-test"] = int.Parse(2); flagsToNumArgs["-out"] = int.Parse(1); flagsToNumArgs["-lengthPenalty"] = int.Parse(1); flagsToNumArgs["-penaltyType"] = int.Parse(1); flagsToNumArgs["-maxLength"] = int.Parse(1); flagsToNumArgs["-stats"] = int.Parse(2); IDictionary <string, string[]> argMap = StringUtils.ArgsToMap(args, flagsToNumArgs); bool eval = argMap.Contains("-eval"); PrintWriter pw = null; if (argMap.Contains("-out")) { pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream((argMap["-out"])[0]), "GB18030"), true); } log.Info("ChineseCharacterBasedLexicon called with args:"); ChineseTreebankParserParams ctpp = new ChineseTreebankParserParams(); for (int i = 0; i < args.Length; i++) { ctpp.SetOptionFlag(args, i); log.Info(" " + args[i]); } log.Info(); Options op = new Options(ctpp); if (argMap.Contains("-stats")) { string[] statArgs = (argMap["-stats"]); MemoryTreebank rawTrainTreebank = op.tlpParams.MemoryTreebank(); IFileFilter trainFilt = new NumberRangesFileFilter(statArgs[1], false); rawTrainTreebank.LoadPath(new File(statArgs[0]), trainFilt); log.Info("Done reading trees."); MemoryTreebank trainTreebank; if (argMap.Contains("-annotate")) { trainTreebank = new MemoryTreebank(); TreeAnnotator annotator = new TreeAnnotator(ctpp.HeadFinder(), ctpp, op); foreach (Tree tree in rawTrainTreebank) { trainTreebank.Add(annotator.TransformTree(tree)); } log.Info("Done annotating trees."); } else { trainTreebank = rawTrainTreebank; } PrintStats(trainTreebank, pw); System.Environment.Exit(0); } int maxLength = 1000000; // Test.verbose = true; if (argMap.Contains("-norm")) { op.testOptions.lengthNormalization = true; } if (argMap.Contains("-maxLength")) { maxLength = System.Convert.ToInt32((argMap["-maxLength"])[0]); } op.testOptions.maxLength = 120; bool combo = argMap.Contains("-combo"); if (combo) { ctpp.useCharacterBasedLexicon = true; op.testOptions.maxSpanForTags = 10; op.doDep = false; op.dcTags = false; } LexicalizedParser lp = null; ILexicon lex = null; if (argMap.Contains("-parser")) { string[] parserArgs = (argMap["-parser"]); if (parserArgs.Length > 1) { IFileFilter trainFilt = new NumberRangesFileFilter(parserArgs[1], false); lp = LexicalizedParser.TrainFromTreebank(parserArgs[0], trainFilt, op); if (parserArgs.Length == 3) { string filename = parserArgs[2]; log.Info("Writing parser in serialized format to file " + filename + " "); System.Console.Error.Flush(); ObjectOutputStream @out = IOUtils.WriteStreamFromString(filename); @out.WriteObject(lp); @out.Close(); log.Info("done."); } } else { string parserFile = parserArgs[0]; lp = LexicalizedParser.LoadModel(parserFile, op); } lex = lp.GetLexicon(); op = lp.GetOp(); ctpp = (ChineseTreebankParserParams)op.tlpParams; } if (argMap.Contains("-rad")) { ctpp.useUnknownCharacterModel = true; } if (argMap.Contains("-lengthPenalty")) { ctpp.lengthPenalty = double.Parse((argMap["-lengthPenalty"])[0]); } if (argMap.Contains("-penaltyType")) { ctpp.penaltyType = System.Convert.ToInt32((argMap["-penaltyType"])[0]); } if (argMap.Contains("-lex")) { string[] lexArgs = (argMap["-lex"]); if (lexArgs.Length > 1) { IIndex <string> wordIndex = new HashIndex <string>(); IIndex <string> tagIndex = new HashIndex <string>(); lex = ctpp.Lex(op, wordIndex, tagIndex); MemoryTreebank rawTrainTreebank = op.tlpParams.MemoryTreebank(); IFileFilter trainFilt = new NumberRangesFileFilter(lexArgs[1], false); rawTrainTreebank.LoadPath(new File(lexArgs[0]), trainFilt); log.Info("Done reading trees."); MemoryTreebank trainTreebank; if (argMap.Contains("-annotate")) { trainTreebank = new MemoryTreebank(); TreeAnnotator annotator = new TreeAnnotator(ctpp.HeadFinder(), ctpp, op); foreach (Tree tree in rawTrainTreebank) { tree = annotator.TransformTree(tree); trainTreebank.Add(tree); } log.Info("Done annotating trees."); } else { trainTreebank = rawTrainTreebank; } lex.InitializeTraining(trainTreebank.Count); lex.Train(trainTreebank); lex.FinishTraining(); log.Info("Done training lexicon."); if (lexArgs.Length == 3) { string filename = lexArgs.Length == 3 ? lexArgs[2] : "parsers/chineseCharLex.ser.gz"; log.Info("Writing lexicon in serialized format to file " + filename + " "); System.Console.Error.Flush(); ObjectOutputStream @out = IOUtils.WriteStreamFromString(filename); @out.WriteObject(lex); @out.Close(); log.Info("done."); } } else { string lexFile = lexArgs.Length == 1 ? lexArgs[0] : "parsers/chineseCharLex.ser.gz"; log.Info("Reading Lexicon from file " + lexFile); ObjectInputStream @in = IOUtils.ReadStreamFromString(lexFile); try { lex = (ILexicon)@in.ReadObject(); } catch (TypeLoadException) { throw new Exception("Bad serialized file: " + lexFile); } @in.Close(); } } if (argMap.Contains("-test")) { bool segmentWords = ctpp.segment; bool parse = lp != null; System.Diagnostics.Debug.Assert((parse || segmentWords)); // WordCatConstituent.collinizeWords = argMap.containsKey("-collinizeWords"); // WordCatConstituent.collinizeTags = argMap.containsKey("-collinizeTags"); IWordSegmenter seg = null; if (segmentWords) { seg = (IWordSegmenter)lex; } string[] testArgs = (argMap["-test"]); MemoryTreebank testTreebank = op.tlpParams.MemoryTreebank(); IFileFilter testFilt = new NumberRangesFileFilter(testArgs[1], false); testTreebank.LoadPath(new File(testArgs[0]), testFilt); ITreeTransformer subcategoryStripper = op.tlpParams.SubcategoryStripper(); ITreeTransformer collinizer = ctpp.Collinizer(); WordCatEquivalenceClasser eqclass = new WordCatEquivalenceClasser(); WordCatEqualityChecker eqcheck = new WordCatEqualityChecker(); EquivalenceClassEval basicEval = new EquivalenceClassEval(eqclass, eqcheck, "basic"); EquivalenceClassEval collinsEval = new EquivalenceClassEval(eqclass, eqcheck, "collinized"); IList <string> evalTypes = new List <string>(3); bool goodPOS = false; if (segmentWords) { evalTypes.Add(WordCatConstituent.wordType); if (ctpp.segmentMarkov && !parse) { evalTypes.Add(WordCatConstituent.tagType); goodPOS = true; } } if (parse) { evalTypes.Add(WordCatConstituent.tagType); evalTypes.Add(WordCatConstituent.catType); if (combo) { evalTypes.Add(WordCatConstituent.wordType); goodPOS = true; } } TreeToBracketProcessor proc = new TreeToBracketProcessor(evalTypes); log.Info("Testing..."); foreach (Tree goldTop in testTreebank) { Tree gold = goldTop.FirstChild(); IList <IHasWord> goldSentence = gold.YieldHasWord(); if (goldSentence.Count > maxLength) { log.Info("Skipping sentence; too long: " + goldSentence.Count); continue; } else { log.Info("Processing sentence; length: " + goldSentence.Count); } IList <IHasWord> s; if (segmentWords) { StringBuilder goldCharBuf = new StringBuilder(); foreach (IHasWord aGoldSentence in goldSentence) { StringLabel word = (StringLabel)aGoldSentence; goldCharBuf.Append(word.Value()); } string goldChars = goldCharBuf.ToString(); s = seg.Segment(goldChars); } else { s = goldSentence; } Tree tree; if (parse) { tree = lp.ParseTree(s); if (tree == null) { throw new Exception("PARSER RETURNED NULL!!!"); } } else { tree = Edu.Stanford.Nlp.Trees.Trees.ToFlatTree(s); tree = subcategoryStripper.TransformTree(tree); } if (pw != null) { if (parse) { tree.PennPrint(pw); } else { IEnumerator sentIter = s.GetEnumerator(); for (; ;) { Word word = (Word)sentIter.Current; pw.Print(word.Word()); if (sentIter.MoveNext()) { pw.Print(" "); } else { break; } } } pw.Println(); } if (eval) { ICollection ourBrackets; ICollection goldBrackets; ourBrackets = proc.AllBrackets(tree); goldBrackets = proc.AllBrackets(gold); if (goodPOS) { Sharpen.Collections.AddAll(ourBrackets, TreeToBracketProcessor.CommonWordTagTypeBrackets(tree, gold)); Sharpen.Collections.AddAll(goldBrackets, TreeToBracketProcessor.CommonWordTagTypeBrackets(gold, tree)); } basicEval.Eval(ourBrackets, goldBrackets); System.Console.Out.WriteLine("\nScores:"); basicEval.DisplayLast(); Tree collinsTree = collinizer.TransformTree(tree); Tree collinsGold = collinizer.TransformTree(gold); ourBrackets = proc.AllBrackets(collinsTree); goldBrackets = proc.AllBrackets(collinsGold); if (goodPOS) { Sharpen.Collections.AddAll(ourBrackets, TreeToBracketProcessor.CommonWordTagTypeBrackets(collinsTree, collinsGold)); Sharpen.Collections.AddAll(goldBrackets, TreeToBracketProcessor.CommonWordTagTypeBrackets(collinsGold, collinsTree)); } collinsEval.Eval(ourBrackets, goldBrackets); System.Console.Out.WriteLine("\nCollinized scores:"); collinsEval.DisplayLast(); System.Console.Out.WriteLine(); } } if (eval) { basicEval.Display(); System.Console.Out.WriteLine(); collinsEval.Display(); } } }
/// <summary>Run the scoring metric on guess/gold input.</summary> /// <remarks> /// Run the scoring metric on guess/gold input. This method performs "Collinization." /// The default language is English. /// </remarks> /// <param name="args"/> public static void Main(string[] args) { if (args.Length < minArgs) { System.Console.Out.WriteLine(usage.ToString()); System.Environment.Exit(-1); } ITreebankLangParserParams tlpp = new EnglishTreebankParserParams(); int maxGoldYield = int.MaxValue; bool Verbose = false; string encoding = "UTF-8"; string guessFile = null; string goldFile = null; IDictionary <string, string[]> argsMap = StringUtils.ArgsToMap(args, optionArgDefs); foreach (KeyValuePair <string, string[]> opt in argsMap) { if (opt.Key == null) { continue; } if (opt.Key.Equals("-l")) { Language lang = Language.ValueOf(opt.Value[0].Trim()); tlpp = lang.@params; } else { if (opt.Key.Equals("-y")) { maxGoldYield = System.Convert.ToInt32(opt.Value[0].Trim()); } else { if (opt.Key.Equals("-v")) { Verbose = true; } else { if (opt.Key.Equals("-c")) { Edu.Stanford.Nlp.Parser.Metrics.TaggingEval.doCatLevelEval = true; } else { if (opt.Key.Equals("-e")) { encoding = opt.Value[0]; } else { log.Info(usage.ToString()); System.Environment.Exit(-1); } } } } } //Non-option arguments located at key null string[] rest = argsMap[null]; if (rest == null || rest.Length < minArgs) { log.Info(usage.ToString()); System.Environment.Exit(-1); } goldFile = rest[0]; guessFile = rest[1]; } tlpp.SetInputEncoding(encoding); PrintWriter pwOut = tlpp.Pw(); Treebank guessTreebank = tlpp.DiskTreebank(); guessTreebank.LoadPath(guessFile); pwOut.Println("GUESS TREEBANK:"); pwOut.Println(guessTreebank.TextualSummary()); Treebank goldTreebank = tlpp.DiskTreebank(); goldTreebank.LoadPath(goldFile); pwOut.Println("GOLD TREEBANK:"); pwOut.Println(goldTreebank.TextualSummary()); Edu.Stanford.Nlp.Parser.Metrics.TaggingEval metric = new Edu.Stanford.Nlp.Parser.Metrics.TaggingEval("Tagging LP/LR"); ITreeTransformer tc = tlpp.Collinizer(); //The evalb ref implementation assigns status for each tree pair as follows: // // 0 - Ok (yields match) // 1 - length mismatch // 2 - null parse e.g. (()). // //In the cases of 1,2, evalb does not include the tree pair in the LP/LR computation. IEnumerator <Tree> goldItr = goldTreebank.GetEnumerator(); IEnumerator <Tree> guessItr = guessTreebank.GetEnumerator(); int goldLineId = 0; int guessLineId = 0; int skippedGuessTrees = 0; while (guessItr.MoveNext() && goldItr.MoveNext()) { Tree guessTree = guessItr.Current; IList <ILabel> guessYield = guessTree.Yield(); guessLineId++; Tree goldTree = goldItr.Current; IList <ILabel> goldYield = goldTree.Yield(); goldLineId++; // Check that we should evaluate this tree if (goldYield.Count > maxGoldYield) { skippedGuessTrees++; continue; } // Only trees with equal yields can be evaluated if (goldYield.Count != guessYield.Count) { pwOut.Printf("Yield mismatch gold: %d tokens vs. guess: %d tokens (lines: gold %d guess %d)%n", goldYield.Count, guessYield.Count, goldLineId, guessLineId); skippedGuessTrees++; continue; } Tree evalGuess = tc.TransformTree(guessTree); Tree evalGold = tc.TransformTree(goldTree); metric.Evaluate(evalGuess, evalGold, ((Verbose) ? pwOut : null)); } if (guessItr.MoveNext() || goldItr.MoveNext()) { System.Console.Error.Printf("Guess/gold files do not have equal lengths (guess: %d gold: %d)%n.", guessLineId, goldLineId); } pwOut.Println("================================================================================"); if (skippedGuessTrees != 0) { pwOut.Printf("%s %d guess trees\n", "Unable to evaluate", skippedGuessTrees); } metric.Display(true, pwOut); pwOut.Println(); pwOut.Close(); }
/// <summary> /// The main method reads (segmented, whitespace delimited) words from a file /// and prints them with their English translation(s). /// </summary> /// <remarks> /// The main method reads (segmented, whitespace delimited) words from a file /// and prints them with their English translation(s). /// The path and filename of the CEDict Lexicon can be supplied via the /// "-dictPath" flag; otherwise the default filename "cedict_ts.u8" in the /// current directory is checked. /// By default, only the first translation is printed. If the "-all" flag /// is given, all translations are printed. /// The input and output encoding can be specified using the "-encoding" flag. /// Otherwise UTF-8 is assumed. /// </remarks> /// <exception cref="System.IO.IOException"/> public static void Main(string[] args) { IDictionary <string, int> flagsToNumArgs = Generics.NewHashMap(); flagsToNumArgs["-dictPath"] = 1; flagsToNumArgs["-encoding"] = 1; IDictionary <string, string[]> argMap = StringUtils.ArgsToMap(args, flagsToNumArgs); string[] otherArgs = argMap[null]; if (otherArgs.Length < 1) { log.Info("usage: ChineseEnglishWordMap [-all] [-dictPath path] [-encoding enc_string] inputFile"); System.Environment.Exit(1); } string filename = otherArgs[0]; bool allTranslations = argMap.Contains("-all"); string charset = defaultCharset; if (argMap.Contains("-encoding")) { charset = argMap["-encoding"][0]; } BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(filename), charset)); ITreebankLanguagePack tlp = new ChineseTreebankLanguagePack(); string[] dpString = argMap["-dictPath"]; ChineseEnglishWordMap cewm = (dpString == null) ? new ChineseEnglishWordMap() : new ChineseEnglishWordMap(dpString[0]); int totalWords = 0; int coveredWords = 0; PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.Console.Out, charset), true); for (string line = r.ReadLine(); line != null; line = r.ReadLine()) { string[] words = line.Split("\\s", 1000); foreach (string word in words) { totalWords++; if (word.Length == 0) { continue; } pw.Print(StringUtils.Pad(word + ':', 8)); if (tlp.IsPunctuationWord(word)) { totalWords--; pw.Print(word); } else { if (IsDigits(word)) { pw.Print(word + " [NUMBER]"); } else { if (cewm.ContainsKey(word)) { coveredWords++; if (allTranslations) { IList <string> trans = new List <string>(cewm.GetAllTranslations(word)); foreach (string s in trans) { pw.Print((trans.IndexOf(s) > 0 ? "|" : string.Empty) + s); } } else { pw.Print(cewm.GetFirstTranslation(word)); } } else { pw.Print("[UNK]"); } } } pw.Println(); } pw.Println(); } r.Close(); log.Info("Finished translating " + totalWords + " words ("); log.Info(coveredWords + " were in dictionary)."); }
/// <summary>Prints out all matches of a semgrex pattern on a file of dependencies.</summary> /// <remarks> /// Prints out all matches of a semgrex pattern on a file of dependencies. /// <p> /// Usage:<br /> /// java edu.stanford.nlp.semgraph.semgrex.SemgrexPattern [args] /// <br /> /// See the help() function for a list of possible arguments to provide. /// </remarks> /// <exception cref="System.IO.IOException"/> public static void Main(string[] args) { IDictionary <string, int> flagMap = Generics.NewHashMap(); flagMap[Pattern] = 1; flagMap[TreeFile] = 1; flagMap[Mode] = 1; flagMap[Extras] = 1; flagMap[ConlluFile] = 1; flagMap[OutputFormatOption] = 1; IDictionary <string, string[]> argsMap = StringUtils.ArgsToMap(args, flagMap); // args = argsMap.get(null); // TODO: allow patterns to be extracted from a file if (!(argsMap.Contains(Pattern)) || argsMap[Pattern].Length == 0) { Help(); System.Environment.Exit(2); } Edu.Stanford.Nlp.Semgraph.Semgrex.SemgrexPattern semgrex = Edu.Stanford.Nlp.Semgraph.Semgrex.SemgrexPattern.Compile(argsMap[Pattern][0]); string modeString = DefaultMode; if (argsMap.Contains(Mode) && argsMap[Mode].Length > 0) { modeString = argsMap[Mode][0].ToUpper(); } SemanticGraphFactory.Mode mode = SemanticGraphFactory.Mode.ValueOf(modeString); string outputFormatString = DefaultOutputFormat; if (argsMap.Contains(OutputFormatOption) && argsMap[OutputFormatOption].Length > 0) { outputFormatString = argsMap[OutputFormatOption][0].ToUpper(); } SemgrexPattern.OutputFormat outputFormat = SemgrexPattern.OutputFormat.ValueOf(outputFormatString); bool useExtras = true; if (argsMap.Contains(Extras) && argsMap[Extras].Length > 0) { useExtras = bool.ValueOf(argsMap[Extras][0]); } IList <SemanticGraph> graphs = Generics.NewArrayList(); // TODO: allow other sources of graphs, such as dependency files if (argsMap.Contains(TreeFile) && argsMap[TreeFile].Length > 0) { foreach (string treeFile in argsMap[TreeFile]) { log.Info("Loading file " + treeFile); MemoryTreebank treebank = new MemoryTreebank(new TreeNormalizer()); treebank.LoadPath(treeFile); foreach (Tree tree in treebank) { // TODO: allow other languages... this defaults to English SemanticGraph graph = SemanticGraphFactory.MakeFromTree(tree, mode, useExtras ? GrammaticalStructure.Extras.Maximal : GrammaticalStructure.Extras.None); graphs.Add(graph); } } } if (argsMap.Contains(ConlluFile) && argsMap[ConlluFile].Length > 0) { CoNLLUDocumentReader reader = new CoNLLUDocumentReader(); foreach (string conlluFile in argsMap[ConlluFile]) { log.Info("Loading file " + conlluFile); IEnumerator <SemanticGraph> it = reader.GetIterator(IOUtils.ReaderFromString(conlluFile)); while (it.MoveNext()) { SemanticGraph graph = it.Current; graphs.Add(graph); } } } foreach (SemanticGraph graph_1 in graphs) { SemgrexMatcher matcher = semgrex.Matcher(graph_1); if (!matcher.Find()) { continue; } if (outputFormat == SemgrexPattern.OutputFormat.List) { log.Info("Matched graph:" + Runtime.LineSeparator() + graph_1.ToString(SemanticGraph.OutputFormat.List)); int i = 1; bool found = true; while (found) { log.Info("Match " + i + " at: " + matcher.GetMatch().ToString(CoreLabel.OutputFormat.ValueIndex)); IList <string> nodeNames = Generics.NewArrayList(); Sharpen.Collections.AddAll(nodeNames, matcher.GetNodeNames()); nodeNames.Sort(); foreach (string name in nodeNames) { log.Info(" " + name + ": " + matcher.GetNode(name).ToString(CoreLabel.OutputFormat.ValueIndex)); } log.Info(" "); found = matcher.Find(); } } else { if (outputFormat == SemgrexPattern.OutputFormat.Offset) { if (graph_1.VertexListSorted().IsEmpty()) { continue; } System.Console.Out.Printf("+%d %s%n", graph_1.VertexListSorted()[0].Get(typeof(CoreAnnotations.LineNumberAnnotation)), argsMap[ConlluFile][0]); } } } }