### Start NER server with a model on disk Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Command-line example to run the NER server with a specific model loaded from disk using the -loadClassifier flag. ```bash java -mx1000m -cp stanford-ner.jar:lib/* edu.stanford.nlp.ie.NERServer -loadClassifier classifiers/all.3class.crf.ser.gz 1234 ``` -------------------------------- ### Run example demo with Maven exec Source: https://github.com/stanfordnlp/corenlp/blob/main/examples/sample-maven-project/README.txt Runs the example demo application using the Maven exec plugin. Replace the main class with your own if needed. ```bash mvn exec:java -Dexec.mainClass="edu.stanford.nlp.StanfordCoreNLPEnglishTestApp" ``` -------------------------------- ### Start NER server on socket 1234 Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Command-line example to run the NER code as a server listening on a socket. The server listens on port 1234 and uses the default model. ```bash java -mx1000m -cp stanford-ner.jar:lib/* edu.stanford.nlp.ie.NERServer 1234 ``` -------------------------------- ### Start NER server with a model as a resource in a jar Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Command-line example to run the NER server with a model loaded as a resource from inside a jar file, using the -loadClassifier flag with a resource path like models/all.3class.crf.ser.gz. ```bash java -mx1000m -cp stanford-ner.jar:lib/* edu.stanford.nlp.ie.NERServer -loadClassifier models/all.3class.crf.ser.gz 1234 ``` -------------------------------- ### Example tree used in all examples Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tsurgeon/README-tsurgeon.txt The sample tree used for the delete, prune, and excise examples. ```tsurgeon (ROOT (S (NP (NNP Maria_Eugenia_Ochoa_Garcia)) (VP (VBD was) (VP (VBN arrested) (PP (IN in) (NP (NNP May))))) (. .))) ``` -------------------------------- ### Create a GraphicalModel Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/loglinear/QUICKSTART.txt Constructs an empty GraphicalModel instance, which is the starting point for training and inference. ```java GraphicalModel model = new GraphicalModel(); ``` -------------------------------- ### Full collapsed dependency output for example sentence Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.tex The complete set of collapsed dependencies for the example sentence, including the collapsed preposition and conjunction relations. ```text nsubj(makes-11, Bell-1) det(company-4, a-3) appos(Bell-1, company-4) nsubjpass(based-7, company-4) auxpass(based-7, is-6) rcmod(company-4, based-7) prep_in(based-7, LA-9) root(ROOT-0, makes-11) conj_and(makes-11, distributes-13) nn(products-15, computer-14) dobj(makes-11, products-15) ``` -------------------------------- ### Example usage of the hybrid coreference system Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/coref/hybrid/README.txt Example code to use the system programmatically. Requires a CoreNLP pipeline and the hcoref annotator. The code creates a CorefSystem, makes a Document, runs coreference resolution, and sets the result annotation. ```java import edu.stanford.nlp.hcoref.CorefCoreAnnotations; import edu.stanford.nlp.hcoref.CorefSystem; import edu.stanford.nlp.hcoref.data.CorefChain; import edu.stanford.nlp.hcoref.data.CorefChain.CorefMention; import edu.stanford.nlp.hcoref.data.Document; CorefSystem corefSystem = new CorefSystem(props); Document corefDoc = corefSystem.docMaker.makeDocument(annotation); Map result = corefSystem.coref(corefDoc); annotation.set(CorefCoreAnnotations.CorefChainAnnotation.class, result); ``` -------------------------------- ### Install Spanish models jar with Maven: mvn install:install-file Source: https://github.com/stanfordnlp/corenlp/blob/main/README.md Installs a language-specific models jar into the local Maven repository. Change the language name in the file path and classifier for other languages; use -Dclassifier=models for the default models jar. ```bash mvn install:install-file -Dfile=/location/of/stanford-spanish-corenlp-models-current.jar -DgroupId=edu.stanford.nlp -DartifactId=stanford-corenlp -Dversion=4.6.0 -Dclassifier=models-spanish -Dpackaging=jar ``` -------------------------------- ### Load serialized NERClassifierCombiner and run on CONLL data Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Command-line example that loads a serialized NERClassifierCombiner (example.serialized.ncc.ncc.ser.gz) and runs it on the sample CONLL data using the -map word=0,answer=1 flag. ```bash java -mx2g edu.stanford.nlp.ie.NERClassifierCombiner -loadClassifier \ classifiers/example.serialized.ncc.ncc.ser.gz -map word=0,answer=1 \ -testFile sample-conll-file.txt ``` -------------------------------- ### excise operation example (VP to PP) Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tsurgeon/README-tsurgeon.txt Applies excise to remove nodes from the VP to the PP, adding the PP's children as children of the VP's parent. ```tsurgeon VP=verb < PP=prep excise verb prep ``` ```tsurgeon (ROOT (S (NP (NNP Maria_Eugenia_Ochoa_Garcia)) (VP (VBD was) (IN in) (NP (NNP May))) (. .))) ``` -------------------------------- ### Run NERDemo programmatically Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Command-line example for running the NERDemo program, which illustrates programmatic use of the NER system. It uses the stanford-ner.jar and lib/* on the classpath, with -mx300m memory, and should produce the same results as using CRFClassifier. ```bash java -cp stanford-ner.jar:lib/*:. -mx300m NERDemo classifiers/english.all.3class.distsim.crf.ser.gz sample.txt ``` -------------------------------- ### Tsurgeon script format example Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tsurgeon/README-tsurgeon.txt Example of a correctly formatted Tsurgeon script: the first line is the Tregex pattern, followed by a blank line, then one Tsurgeon operation per line without blank lines between operations. ```tsurgeon S < NP=node < NNP=name relabel node NP_NAME coindex node name ``` -------------------------------- ### Initialize PUA normalization script Source: https://github.com/stanfordnlp/corenlp/wiki/Chinese-Private-Use-Area-code-points Initializes the normalization script with imports and an empty conversion dictionary. This is the starting point for the PUA normalization utility. ```Python #!/usr/bin/env python3 # -*- coding: utf-8 -*- '''Normalizes PUA code points generated by decoders. Released under CC0.''' import argparse import os import sys conv = {} ``` -------------------------------- ### Serialize NERClassifierCombiner with HIGH_RECALL and SUTime disabled Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Command-line example that loads three sample CRFs with combinationMode=HIGH_RECALL and SUTime=false, then serializes the combined classifier to a file named test.serialized.ncc.ncc.ser.gz. ```bash java -mx2g edu.stanford.nlp.ie.NERClassifierCombiner -ner.model \ classifiers/english.conll.4class.distsim.crf.ser.gz,classifiers/english.muc.7class.distsim.crf.ser.gz,\ classifiers/english.all.3class.distsim.crf.ser.gz -ner.useSUTime false \ -ner.combinationMode HIGH_RECALL -serializeTo test.serialized.ncc.ncc.ser.gz ``` -------------------------------- ### excise operation example (PP) Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tsurgeon/README-tsurgeon.txt Applies excise to remove the PP node and add its children in its place. The children of the second node become children of the parent of the first node. ```tsurgeon VP < PP=prep excise prep prep ``` ```tsurgeon (ROOT (S (NP (NNP Maria_Eugenia_Ochoa_Garcia)) (VP (VBD was) (VP (VBN arrested) (IN in) (NP (NNP May))))) (. .))) ``` -------------------------------- ### Build CoreNLP with Maven: mvn package Source: https://github.com/stanfordnlp/corenlp/blob/main/README.md Builds the CoreNLP jar file (stanford-corenlp-4.6.0.jar) and runs tests. Requires Maven installed. ```bash mvn package ``` -------------------------------- ### Run NERClassifierCombiner on CONLL-style input Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Command-line example for running the combined CRFs on a CONLL-style test file. The -map word=0,answer=1 flag is crucial, specifying that the input file has words in the first column and answer labels in the second column. ```bash java -mx2g edu.stanford.nlp.ie.NERClassifierCombiner -ner.model \ classifiers/english.conll.4class.distsim.crf.ser.gz,classifiers/english.muc.7class.distsim.crf.ser.gz \ -map word=0,answer=1 -testFile sample-conll-file.txt ``` -------------------------------- ### Basic typed dependencies for example sentence Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.tex Basic typed dependencies for the example sentence 'Bell, a company which is based in LA, makes and distributes computer products.' Each dependency is in the format relation(governor, dependent) with word indices appended. This representation forms a tree structure where each word is a dependent of exactly one other token or the ROOT-0 token. ```text nsubj(makes-11, Bell-1) det(company-4, a-3) appos(Bell-1, company-4) nsubjpass(based-7, which-5) auxpass(based-7, is-6) rcmod(company-4, based-7) prep(based-7, in-8) pobj(in-8, LA-9) root(ROOT-0, makes-11) cc(makes-11, and-12) conj(makes-11, distributes-13) nn(products-15, computer-14) dobj(makes-11, products-15) ``` -------------------------------- ### delete operation example Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tsurgeon/README-tsurgeon.txt Applies delete to remove the PP node directly dominated by a VP. The PP node and everything under it are removed. ```tsurgeon VP < PP=prep delete prep ``` ```tsurgeon (ROOT (S (NP (NNP Maria_Eugenia_Ochoa_Garcia)) (VP (VBD was) (VP (VBN arrested) (. .))) ``` -------------------------------- ### Java API example for LexicalizedParser Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.pdf This Java code demonstrates how to load the parser model and obtain typed dependencies from a sentence. It uses the PennTreebankLanguagePack and can optionally generate original Stanford Dependencies by uncommenting the line. The resulting dependencies are printed to standard output. ```java LexicalizedParser lp = LexicalizedParser.loadModel( "edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz", "-maxLength", "80", "-retainTmpSubcategories"); TreebankLanguagePack tlp = new PennTreebankLanguagePack(); // Uncomment the following line to obtain original Stanford Dependencies // tlp.setGenerateOriginalDependencies(true); GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory(); String[] sent = "This", "is", "an", "easy", "sentence", "."; Tree parse = lp.apply(Sentence.toWordList(sent)); GrammaticalStructure gs = gsf.newGrammaticalStructure(parse); Collection tdl = gs.typedDependencies(); System.out.println(tdl); ``` -------------------------------- ### Download French models via git-lfs: git clone https://huggingface.co/stanfordnlp/corenlp-french Source: https://github.com/stanfordnlp/corenlp/blob/main/README.md Downloads the French models jar from Hugging Face Hub using git-lfs. Requires git-lfs installed. Replace 'corenlp-french' with the desired language repository. ```bash # Make sure you have git-lfs installed # (https://git-lfs.github.com/) git lfs install git clone https://huggingface.co/stanfordnlp/corenlp-french ``` -------------------------------- ### Command line usage for EnglishGrammaticalStructure Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.pdf Command line example for parsing a sentence file with the EnglishGrammaticalStructure class, specifying options for collapsed tree, CCprocessed, parse tree, and parser file. ```bash java-mx100m edu.stanford.nlp.trees.EnglishGrammaticalStructure -sentFile file.txt-collapsedTree-CCprocessed-parseTree-parserFile englishPCFG.ser.gz ``` -------------------------------- ### Non-collapsed dependencies Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.tex Example of non-collapsed dependency output. This representation gives basic dependencies plus extra ones that break the tree structure, without collapsing or propagation of conjuncts. The extra dependencies can be separated from basic ones at print time. ```text nsubj(makes-11, Bell-1) det(company-4, a-3) appos(Bell-1, company-4) nsubjpass(based-7, which-5) auxpass(based-7, is-6) rcmod(company-4, based-7) prep(based-7, in-8) pobj(in-8, LA-9) root(ROOT-0, makes-11) cc(makes-11, and-12) conj(makes-11, distributes-13) nn(products-15, computer-14) dobj(makes-11, products-15) ====== ref(company-4, which-5) ``` -------------------------------- ### Copy nodes in collapsed dependencies Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.tex Example of collapsed dependency output showing copy nodes introduced for PP conjunction. A copy node is marked with an apostrophe in plain text output or a 'copy' attribute in XML output. This example corresponds to a sentence like 'Bill went over the river and went through the woods'. ```text prep_over(went-2, river-5) prep_through(went-2’, woods-10) conj_and(went-2, went-2’) ``` -------------------------------- ### Run NERClassifierCombiner on text file with two CRFs Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Command-line example that combines two CRF models (CONLL 4-class and MUC 7-class) and disables SUTime. The -ner.model flag takes a comma-separated list of serialized CRFs. When -ner.useSUTime false is omitted, phrases like '4 days ago' are tagged with DATE. ```bash java -mx2g edu.stanford.nlp.ie.NERClassifierCombiner -ner.model \ classifiers/english.conll.4class.distsim.crf.ser.gz,classifiers/english.muc.7class.distsim.crf.ser.gz \ -ner.useSUTime false -textFile sample-w-time.txt ``` -------------------------------- ### Composite Rule Defaults and Example Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/time/rules/english.sutime.txt Sets the default rule type to 'composite' and defines a composite rule that applies a relative modifier to a temporal expression, producing a relative time. ```sutime ENV.defaults["ruleType"] = "composite" ``` ```sutime { name: "temporal-composite-6b", priority: 20, pattern: ( ( $REL_MOD ) ( [ $hasTemporal & !{ temporal::IS_TIMEX_SET } ] ) ), result: RelativeTime( GetTag($1[0], "TemporalOp"), $2[0].temporal.value ) } ``` -------------------------------- ### Named nodes in trees Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tsurgeon/README-tsurgeon.txt Nodes can be named by appending = to the label. The name can be referred to by subsequent tsurgeon operations. Example shows inserting an NP trace and coindexing it with a node named 'antecedent'. ```tsurgeon insert (NP (-NONE- *T*=trace)) coindex trace antecedent $ ``` -------------------------------- ### prune operation example Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tsurgeon/README-tsurgeon.txt Applies prune to remove the NNP node. Since the NP above it becomes empty, the NP node is also deleted. This differs from delete, which would leave the empty NP. ```tsurgeon S < (NP < NNP=noun) prune noun ``` ```tsurgeon (ROOT (S (VP (VBD was) (VP (VBN arrested) (PP (IN in) (NP (NNP May))))) (. .))) ``` -------------------------------- ### Command-line usage of LexicalizedParser with dependency options Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.pdf Use this command to parse sentences from a file, specifying the output format as penn and typedDependencies, with options for basic dependencies. The -retainTmpSubcategories option is recommended for temporal dependencies. The -originalDependencies option can be used to get original Stanford Dependencies instead of Universal Dependencies. ```bash java -mx200m edu.stanford.nlp.parser.lexparser.LexicalizedParser -retainTmpSubcategories -originalDependencies -outputFormat "penn,typedDependencies" -outputFormatOptions "basicDependencies" englishPCFG.ser.gz file.txt ``` -------------------------------- ### Early/Late Modifiers Rules Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/time/rules/english.sutime.txt Defines rules for tagging early/late modifiers such as 'late', 'end', 'early', 'beginning', 'start', 'dawn', 'mid-', 'middle' with corresponding modifier tags. ```sutime { pattern: ( /late/ | /end/ ), action: Tag($0, "Modifier", "LATE") } ``` ```sutime { pattern: ( /early/ | /beginning|start|dawn/ ), action: Tag($0, "Modifier", "EARLY") } ``` ```sutime { pattern: ( /mid-?/ | /middle/ ), action: Tag($0, "Modifier", "MID") } ``` -------------------------------- ### Rule for approximate durations like 'recent weeks' Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/time/rules/english.sutime.txt Matches phrases like 'recent weeks' or 'several days' and produces an InexactDuration with an unspecified start and end, using the matched time unit. ```tokensregex { pattern: ( (/recent|several/) /-/? ([ { temporal::IS_TIME_UNIT } ]) ), result: InexactDuration( Duration(NIL, NIL, $2) ) } ``` -------------------------------- ### Run the MaxentTaggerGUI demonstration Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tagger/README.txt Two ways to launch the demonstration GUI: directly with the Java command or via the provided scripts for Windows and Unix-like systems. The GUI is for demonstration only; most features are only accessible from the command line. ```bash java -mx200m -classpath stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTaggerGUI models/wsj-0-18-left3words-distsim.tagger ``` ```bash stanford-postagger-gui.bat ./stanford-postagger-gui.sh ``` -------------------------------- ### Tsurgeon relabel with regex: /^VB.+/=v Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tsurgeon/README-tsurgeon.txt This uses a regex-based relabel. It matches all nodes whose label starts with 'VB' and at least one more character, then relabels each matched node using the first regex group (everything after 'VB'). The result changes 'VBD' to 'D' and 'VBN' to 'N'. ```tsurgeon /^VB.+/=v relabel v /^VB(.*)$/ #1 ``` -------------------------------- ### Tregex pattern with variable group coindexation Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tregex/README-tregex.txt Example pattern for Penn Treebank trees that enforces coindexation: matches only when the WH- node under the SBAR is coindexed with the trace node that gets the name 'empty'. ```tregex @SBAR < /^WH.*-([0-9]+)$/#1%index<<(__=empty < (/^-NONE-/< /^\*T\*-([0-9]+)$/#1%index)) ``` -------------------------------- ### Tag a file with the provided script Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tagger/README.txt Run the tagger from the command line using the provided scripts for Unix-like and Windows systems. The output should match the contents of sample-output.txt. ```bash ./stanford-postagger.sh models/wsj-0-18-left3words-distsim.tagger sample-input.txt ``` ```bash stanford-postagger models\wsj-0-18-left3words-distsim.tagger sample-input.txt ``` -------------------------------- ### Enable per-sentence domains with -withDomains Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/segmenter/README-Arabic.txt Enables per-sentence dialect specification. Each line must begin with 'atb' (MSA) or 'arz' (Egyptian) followed by a space before the sentence text. ```bash -withDomains ``` -------------------------------- ### Rebuild Models with make Source: https://github.com/stanfordnlp/corenlp/blob/main/scripts/truecase/readme.txt His a make command to rebuild the truecase models. Requires a machine with large RAM. ```bash run make ``` -------------------------------- ### Tregex pattern with negated relation '!<' Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tregex/README-tregex.txt Negated relation example: matches only NPs that do not dominate an NNP. ```tregex (NP !< NNP) ``` -------------------------------- ### Define annotation classes and environment defaults Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/ling/tokensregex/demo/rules/expr.rules.txt Sets up annotation keys for original text, numeric tokens, and custom annotations, and configures the default result annotation key and nested results key. ```tokensregex orig = { type: "CLASS", value: "edu.stanford.nlp.ling.CoreAnnotations$OriginalTextAnnotation" } numtokens = { type: "CLASS", value: "edu.stanford.nlp.ling.CoreAnnotations$NumerizedTokensAnnotation" } numcomptype = { type: "CLASS", value: "edu.stanford.nlp.ling.CoreAnnotations$NumericCompositeTypeAnnotation" } numcompvalue = { type: "CLASS", value: "edu.stanford.nlp.ling.CoreAnnotations$NumericCompositeValueAnnotation" } mytokens = { type: "CLASS", value: "edu.stanford.nlp.ling.tokensregex.demo.MyAnnotations$MyTokensAnnotation" } type = { type: "CLASS", value: "edu.stanford.nlp.ling.tokensregex.demo.MyAnnotations$MyTypeAnnotation" } value = { type: "CLASS", value: "edu.stanford.nlp.ling.tokensregex.demo.MyAnnotations$MyValueAnnotation" } ENV.defaultResultAnnotationKey = ( type, value ) ENV.defaultNestedResultsAnnotationKey = mytokens ENV.defaults["stage.limitIters"] = 0 ``` -------------------------------- ### Tregex pattern with negated label '!NNP|NNS' Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tregex/README-tregex.txt Negated label description example: matches NPs dominating some node that is not an NNP or an NNS. ```tregex (NP < !NNP|NNS) ``` -------------------------------- ### Train a simple model Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tagger/README.txt Train a new model based on a set of tagged data. Requires a properties file, a model file, and a training file. ```bash java -classpath stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTagger -prop propertiesFile -model modelFile -trainFile trainingFile ``` -------------------------------- ### Collapsed dependency transformation for preposition 'in' Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.tex Shows how the basic dependencies 'prep(based-7, in-8)' and 'pobj(in-8, LA-9)' are collapsed into a single relation 'prep_in(based-7, LA-9)'. ```text prep(based-7, in-8) ``` ```text pobj(in-8, LA-9) ``` ```text prep_in(based-7, LA-9) ``` -------------------------------- ### Run Spanish neural dependency parser Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Command to run the Spanish neural dependency parser on pre-tokenized UD 2.0 text. Requires the '-tokenized' flag and a text file with whitespace-separated tokens. ```bash java -Xmx2g -cp "*" edu.stanford.nlp.parser.nndep.DependencyParser \ -model edu/stanford/nlp/models/parser/nndep/UD_Spanish.gz \ -tagger.model edu/stanford/nlp/models/pos-tagger/spanish-ud.tagger \ -tokenized -textFile example.txt -outFile example.txt.out ``` -------------------------------- ### Run TreebankPreprocessor for ATB data Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Command to create the ATB data using the TreebankPreprocessor. Requires updating the conf file paths to local treebank distributions and setting the classpath in the cmd_line variable of run-tb-preproc. ```bash bin/run-tb-preproc -v conf/atb-latest.conf ``` -------------------------------- ### Run parser with multilingual grammars Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Runs the parser with trained grammars for Arabic, Chinese, French, and German. ```bash lexparser-lang.sh ``` -------------------------------- ### Parallelize domain-adapted training with -multiThreadGrad Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/segmenter/README-Arabic.txt Add this option to the domain-adapted training command to parallelize gradient computation across threads. ```bash -multiThreadGrad ``` -------------------------------- ### Run French neural dependency parser Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Command to run the French neural dependency parser on pre-tokenized UD 2.2 text. Requires the '-tokenized' flag and a text file with whitespace-separated tokens. ```bash java -Xmx2g -cp "*" edu.stanford.nlp.parser.nndep.DependencyParser \ -model edu/stanford/nlp/models/parser/nndep/UD_French.gz \ -tagger.model edu/stanford/nlp/models/pos-tagger/french-ud.tagger \ -tokenized -textFile example.txt -outFile example.txt.out ``` -------------------------------- ### Evaluating the hybrid coreference system Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/coref/hybrid/README.txt Command to evaluate the system. Uses 30GB of memory and outputs to output.txt. ```bash $ java -Xmx30g edu.stanford.nlp.hcoref.CorefSystem -props >& output.txt ``` -------------------------------- ### Run German neural dependency parser Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Command to run the German neural dependency parser on pre-tokenized UD 2.2 text. Requires the '-tokenized' flag and a text file with whitespace-separated tokens. ```bash java -Xmx2g -cp "*" edu.stanford.nlp.parser.nndep.DependencyParser \ -model edu/stanford/nlp/models/parser/nndep/UD_German.gz \ -tagger.model edu/stanford/nlp/models/pos-tagger/german-ud.tagger \ -tokenized -textFile example.txt -outFile example.txt.out ``` -------------------------------- ### Add a factor to a GraphicalModel Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/loglinear/QUICKSTART.txt Adds a factor between variables 2 and 7 with 3 and 2 states respectively. The closure returns an empty ConcatVector and will be replaced by a featurized version in the next example. ```java int[] neighbors = new int[]{2,7}; int[] neighborSizes = new int[]{3,2}; // This must appear in the same order as neighbors model.addFactor(neighbors, neighborSizes, (int[] assignment) -> { // TODO: In the next paragraph we'll discuss featurizing each possible assignment to neighbors return new ConcatVector(0); }); ``` -------------------------------- ### Tokenize Text with StanfordCoreNLP Source: https://github.com/stanfordnlp/corenlp/blob/main/scripts/truecase/readme.txt Tokenizes and splits the raw wiki text into sentences using Stanford CoreNLP with 90GB of memory. The tokenized output is saved to wiki.tokenized.txt. If memory is insufficient, split the input file into smaller pieces first. ```bash nohup java -mx90g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit -file ~/truecase/wiki.raw.txt -ssplit.newlineIsSentenceBreak always -outputFormat tagged > wiki.tokenized.txt ``` -------------------------------- ### Compile Maven project Source: https://github.com/stanfordnlp/corenlp/blob/main/examples/sample-maven-project/README.txt Compiles the Maven project. Use after setting MAVEN_OPTS to ensure the build has enough memory. ```bash mvn compile ``` -------------------------------- ### Tregex pattern with backreference '=comma' Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tregex/README-tregex.txt Backreferencing example: matches only an NP dominating exactly the sequence NP, NP; the mother NP cannot have any other daughters. The named node 'comma' is referenced later with '=comma'. ```tregex (@NP <, (@NP $+ (/,/ $+ (@NP $+ /,/=comma))) <- =comma) ``` -------------------------------- ### Launch parser GUI on Unix Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Launches the parsing GUI on Unix. The GUI is only for exploring the parser and does not allow saving output; use the command-line program or programmatic API for serious work. ```bash lexparser-gui.sh ``` -------------------------------- ### Generate default properties file with -genprops Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tagger/README.txt Generate a default properties file with descriptions of each option and their default values. The file can be used to set options for training, tagging, and testing. ```bash java -classpath stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTagger -genprops > myPropsFile.prop ``` -------------------------------- ### Compile TaggerDemo.java with javac Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tagger/README.txt Compile TaggerDemo.java against the Stanford POS Tagger JAR. Requires Java 1.8 and the stanford-postagger.jar file in the current directory. ```bash javac -cp stanford-postagger.jar TaggerDemo.java ``` -------------------------------- ### Run TaggerDemo with java Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tagger/README.txt Run the compiled TaggerDemo with the left3words model and sample input. On Windows, replace the colon in -cp with a semicolon and use backslashes in file paths. ```bash java -cp ".:stanford-postagger.jar" TaggerDemo models/wsj-0-18-left3words-distsim.tagger sample-input.txt ``` -------------------------------- ### Test a model Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tagger/README.txt Test a model by tagging labeled data and evaluating the results against the correct tags. Requires a properties file, a model file, and a test file. ```bash java -classpath stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTagger -prop propertiesFile -model modelFile -testFile testFile ``` -------------------------------- ### Collapsed dependencies preserving a tree structure Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.tex Example of collapsed dependency output that preserves a tree structure. This representation omits relations that break the tree structure, such as relative clause antecedents, controlling subjects (xsubj), and preposition stranding (pobj). It also does not allow propagation of conjunct dependencies. ```text nsubj(makes-11, Bell-1) det(company-4, a-3) appos(Bell-1, company-4) nsubjpass(based-7, which-5) auxpass(based-7, is-6) rcmod(company-4, based-7) prep_in(based-7, LA-9) root(ROOT-0, makes-11) conj_and(makes-11, distributes-13) nn(products-15, computer-14) dobj(makes-11, products-15) ``` -------------------------------- ### Train Arabic segmenter with L1 regularization options Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/segmenter/README-Arabic.txt Add these options to the training command to use L1 regularization, which reduces model size with a negligible accuracy drop. ```bash -useOWLQN -priorLambda 0.05 ``` -------------------------------- ### ENV defaults and vague time rules Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/time/rules/english.sutime.txt Sets default stage and ruleType, then defines rules that map vague temporal phrases to TIME_PAST, TIME_PRESENT, and TIME_FUTURE categories. ```sutime ENV.defaults["stage"] = 4 ENV.defaults["ruleType"] = "tokens" # Vague times { ( /the/ /past/ | /recently/ ) => TIME_PAST } { pattern: ( /at/ /the/ (/time/) ), matchedExpressionGroup: 1, result: TIME_PAST } { ( /past|once|medieval|previously/ ) => TIME_PAST } { ( /present|current|currently/ | /right/? /now/ ) => TIME_PRESENT } { ( /the/? /near/? /future/ ) => TIME_FUTURE } ``` -------------------------------- ### Run PCFG parser on English test file Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Runs the PCFG parser on the English test file. The parser data takes a few seconds to load before parsing begins; continued parsing is quicker. To use the lexicalized parser, replace englishPCFG.ser.gz with englishFactored.ser.gz in the lexparser.sh script and use the flag -mx600m to give more memory to java. ```bash ./lexparser.sh data/testsent.txt ``` -------------------------------- ### Environment Defaults Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/time/rules/english.sutime.txt Sets default stage and ruleType for the SUTime environment. ```sutime ENV.defaults["stage"] = 1 ENV.defaults["ruleType"] = "text" ``` -------------------------------- ### Train Arabic segmenter with domain adaptation Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/segmenter/README-Arabic.txt Trains a domain-adapted model using a training file with domain labels. Requires significant memory and time; can be parallelized with -multiThreadGrad. ```bash java -Xmx64g -Xms64g edu.stanford.nlp.international.arabic.process.ArabicSegmenter -withDomains -trainFile atb+arz-withDomains-train.utf8.txt -serializeTo my_trained_segmenter.ser.gz ``` -------------------------------- ### API usage to convert Tree to dependencies Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.pdf Java code showing how to set up a TreebankLanguagePack, create a GrammaticalStructureFactory, and obtain typed dependencies from a Tree object. ```java // One time setup TreebankLanguagePack tlp = new PennTreebankLanguagePack(); // Uncomment the following line to obtain original Stanford Dependencies // tlp.setGenerateOriginalDependencies(true); GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory(); // For each Tree Tree parseTree; // assumed to come from a treebank or parser GrammaticalStructure gs = gsf.newGrammaticalStructure(parseTree); Collection tdl = gs.typedDependencies(); ``` -------------------------------- ### Run WikiExtractor on Wikipedia Dump Source: https://github.com/stanfordnlp/corenlp/blob/main/scripts/truecase/readme.txt Executes the WikiExtractor tool in the background on the specified Wikipedia dump file. Directs standard output and error to text.out while the ampersand runs the process asynchronously. ```bash nohup python3 wikiextractor/WikiExtractor.py wiki/enwiki-20190920-pages-articles-multistream.xml > text.out 2>&1 & ``` -------------------------------- ### Run NER on a file using ner.bat (Windows) Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Use the supplied ner.bat script to tag a single file on Windows. The command is 'ner file'. ```bash ner file ``` -------------------------------- ### Set default stage Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/ie/qe/rules/english.qe.txt Sets the default stage to 1. ```jape ENV.defaults["stage"] = 1 ``` -------------------------------- ### Propagated conjunct dependencies for 'distributes' Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.tex Shows the dependencies that should be propagated to the second conjunct 'distributes' due to the conjunction with 'makes'. The converter currently only generates the first one. ```text nsubj(distributes-13, Bell-1) ``` ```text dobj(distributes-13, products-15) ``` -------------------------------- ### Use original Stanford Dependencies flag Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Flag to obtain original Stanford Dependencies instead of the default Universal Dependencies representation (since v3.5.2). ```bash -originalDependencies ``` -------------------------------- ### Set Maven memory with MAVEN_OPTS Source: https://github.com/stanfordnlp/corenlp/blob/main/examples/sample-maven-project/README.txt Sets the Maven JVM heap size to 14 GB before building or running the project. Required to avoid out-of-memory errors when processing large texts with Stanford CoreNLP. ```bash export MAVEN_OPTS="-Xmx14000m" ``` -------------------------------- ### Tag a file with CRFClassifier from command line Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/ner/README.txt Run the CRFClassifier on a text file using the 3-class distsim model. Requires Java 1.8+ and the stanford-ner.jar and lib directory in CLASSPATH. ```bash java -mx600m -cp stanford-ner.jar:lib/* edu.stanford.nlp.ie.crf.CRFClassifier -loadClassifier classifiers/english.all.3class.distsim.crf.ser.gz -textFile sample.txt ``` -------------------------------- ### Train weights with BacktrackingAdaGradOptimizer Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/loglinear/QUICKSTART.txt Trains weights on an array of labeled GraphicalModels using a LogLikelihoodFunction and an AbstractBatchOptimizer. The optimizer returns the optimal ConcatVector of weights. ```java GraphicalModel[] trainingSet = //omitted dataset construction; // Create the optimizer we will use AbstractBatchOptimizer opt = new BacktrackingAdaGradOptimizer(); // Call the optimizer, with a dataset, a function to optimize, initial weights, and l2 regularization constant ConcatVector weights = opt.optimize(trainingSet, new LogLikelihoodFunction(), new ConcatVector(0), 0.1); ``` -------------------------------- ### Run ArabicSegmenter on a text file Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/segmenter/README-Arabic.txt Segments a UTF-8 newline-delimited text file using the ArabicSegmenter. Requires the classifier file data/arabic-segmenter-atb+bn+arztrain.ser.gz and the jars in the unpacked directory on the classpath. Output is written to the file specified after the redirection operator. ```bash java -mx1g edu.stanford.nlp.international.arabic.process.ArabicSegmenter -loadClassifier data/arabic-segmenter-atb+bn+arztrain.ser.gz -textFile my_arabic_file.txt > my_arabic_file.txt.segmented ``` -------------------------------- ### Define SI prefix name map and create regex Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/ie/qe/rules/prefixes.rules.txt Defines a mapping from full SI prefix names to their corresponding constants and creates a regex pattern from the keys. The regex is stored in the variable $SiPrefixes. ```text SI_PREFIX_MAP = { "deca": DECA, "hecto": HECTO, "kilo": KILO, "mega": MEGA, "giga": GIGA, "tera": TERA, "peta": PETA, "exa": EXA, "zetta": ZETTA, "yotta": YOTTA, "deci": DECI, "centi": CENTI, "milli": MILLI, "micro": MICRO, "nano": NANO, "pico": PICO, "femto": FEMTO, "atto": ATTO, "zepto": ZEPTO, "yocto": YOCTO } $SiPrefixes = CreateRegex(Keys(SI_PREFIX_MAP)) ``` -------------------------------- ### Training the hybrid coreference system Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/coref/hybrid/README.txt Command to train all sieves contiguously. Requires the hcoref.train package, weka 3.7.12, and FastRandomForest. Uses 30GB of memory. ```bash $ java -Xmx30g edu.stanford.nlp.hcoref.train.CorefTrainer -props >& log-train.txt ``` -------------------------------- ### Tag a file with the bidirectional model Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/tagger/README.txt Tag a file using the pre-trained bidirectional model. Tagged output is printed to standard out and can be redirected as shown. The bidirectional model is slightly more accurate but significantly slower than the left3words model. ```bash java -mx300m -classpath stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTagger -model models/wsj-0-18-bidirectional-distsim.tagger -textFile sample-input.txt > sample-tagged.txt ``` -------------------------------- ### Run neural net dependency parser on Chinese Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Runs the neural net dependency parser on Chinese text. Requires a language-specific POS tagger, here the Chinese distsim tagger. Output is written to data/chinese-onesent-utf8.txt.out. ```bash java -Xmx2g -cp "*" edu.stanford.nlp.parser.nndep.DependencyParser \ -model edu/stanford/nlp/models/parser/nndep/UD_Chinese.gz \ -tagger.model edu/stanford/nlp/models/pos-tagger/chinese-distsim.tagger \ -textFile data/chinese-onesent-utf8.txt -outFile data/chinese-onesent-utf8.txt.out ``` -------------------------------- ### Java: Extract typed dependencies using LexicalizedParser and GrammaticalStructure Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.tex Java code to load the English PCFG model, parse a sentence, and print typed dependencies. Includes commented line to obtain original Stanford Dependencies. Requires the Stanford parser library. ```java LexicalizedParser lp = LexicalizedParser.loadModel( "edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz", "-maxLength", "80", "-retainTmpSubcategories"); TreebankLanguagePack tlp = new PennTreebankLanguagePack(); // Uncomment the following line to obtain original Stanford Dependencies // tlp.setGenerateOriginalDependencies(true); GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory(); ``` ```java String[] sent = "This", "is", "an", "easy", "sentence", "." ; Tree parse = lp.apply(Sentence.toWordList(sent)); GrammaticalStructure gs = gsf.newGrammaticalStructure(parse); Collection$\langle$TypedDependency$\rangle$ tdl = gs.typedDependencies(); System.out.println(tdl); ``` -------------------------------- ### Run neural net dependency parser on English Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/README.txt Runs the neural net dependency parser on an English sentence. The output is written to data/english-onesent.txt.out. ```bash java -Xmx2g -cp "*" edu.stanford.nlp.parser.nndep.DependencyParser \ -model edu/stanford/nlp/models/parser/nndep/english_UD.gz \ -textFile data/english-onesent.txt -outFile data/english-onesent.txt.out ``` -------------------------------- ### Fiscal Quarter Maps and Year Offsets Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/time/rules/english.sutime.txt Defines FISCAL_YEAR_QUARTER_MAP and FISCAL_YEAR_QUARTER_YEAR_OFFSETS_MAP, then creates a regex for fiscal year quarter terms. The offsets indicate year adjustment for each quarter. ```sutime FISCAL_YEAR_QUARTER_MAP = { "Q1": FYQ1, "Q2": FYQ2, "Q3": FYQ3, "Q4": FYQ4 } FISCAL_YEAR_QUARTER_YEAR_OFFSETS_MAP = { "Q1": 1, "Q2": 0, "Q3": 0, "Q4": 0 } $FiscalYearQuarterTerm = CreateRegex(Keys(FISCAL_YEAR_QUARTER_MAP)) ``` -------------------------------- ### Tag unit mentions with patterns and Tag action Source: https://github.com/stanfordnlp/corenlp/blob/main/src/edu/stanford/nlp/ie/qe/rules/english.units.rules.txt Sets the default stage to 0 and defines a series of token patterns that tag unit mentions with their corresponding unit constants (e.g., MONEY_DOLLAR, LENGTH_METER). Each pattern uses a regex and a Tag action. ```tokensregex ENV.defaults["stage"] = 0 { pattern: ( /dollars?/ ), action: Tag($0, "Unit", MONEY_DOLLAR) } { pattern: ( /cents?/ ), action: Tag($0, "Unit", MONEY_CENT) } { pattern: ( /pounds?/ ), action: Tag($0, "Unit", MONEY_POUND) } { pattern: ( /penny|pennies|pences?/ ), action: Tag($0, "Unit", MONEY_PENNY) } { pattern: ( /yen/ ), action: Tag($0, "Unit", MONEY_YEN) } { pattern: ( /euros?/ ), action: Tag($0, "Unit", MONEY_EURO) } { pattern: ( /yuan/ ), action: Tag($0, "Unit", MONEY_YUAN) } { pattern: ( /meters?/ ), action: Tag($0, "Unit", LENGTH_METER) } { pattern: ( /metres?/ ), action: Tag($0, "Unit", LENGTH_METER) } { pattern: ( /miles?/ ), action: Tag($0, "Unit", LENGTH_MILE) } { pattern: ( /yards?/ ), action: Tag($0, "Unit", LENGTH_YARD) } { pattern: ( /foot|feet/ ), action: Tag($0, "Unit", LENGTH_FOOT) } { pattern: ( /inch(es)?/ ), action: Tag($0, "Unit", LENGTH_INCH) } { pattern: ( /degrees?/? /Fahrenheit/ ), action: Tag($0, "Unit", TEMPERATURE_FAHRENHEIT) } { pattern: ( /degrees?/? /Celsius/ ), action: Tag($0, "Unit", TEMPERATURE_CELSIUS) } { pattern: ( /degrees?/ /F/ ), action: Tag($0, "Unit", TEMPERATURE_FAHRENHEIT) } { pattern: ( /degrees?/ /C/ ), action: Tag($0, "Unit", TEMPERATURE_CELSIUS) } { pattern: ( /°F/ ), action: Tag($0, "Unit", TEMPERATURE_FAHRENHEIT) } { pattern: ( /°C/ ), action: Tag($0, "Unit", TEMPERATURE_CELSIUS) } { pattern: ( /acres?/ ), action: Tag($0, "Unit", AREA_ACRE) } { pattern: ( /litres?/ ), action: Tag($0, "Unit", VOLUME_LITER) } { pattern: ( /liters?/ ), action: Tag($0, "Unit", VOLUME_LITER) } { pattern: ( /tablespoons?/ ), action: Tag($0, "Unit", VOLUME_TABLESPOON) } { pattern: ( /teaspoons?/ ), action: Tag($0, "Unit", VOLUME_TEASPOON) } { pattern: ( /grams?/ ), action: Tag($0, "Unit", WEIGHT_GRAM) } { pattern: ( /pounds?/ ), action: Tag($0, "Unit", WEIGHT_POUND) } ``` -------------------------------- ### Command-line usage with -treeFile Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.tex Runs EnglishGrammaticalStructure on a file of Penn treebank-style trees, outputting collapsed dependencies with CC propagation and keeping punctuation. Requires a parser file specified with -parserFile. ```bash java -mx100m edu.stanford.nlp.trees.EnglishGrammaticalStructure -sentFile file.txt -collapsedTree -CCprocessed -parseTree -parserFile englishPCFG.ser.gz ``` -------------------------------- ### Methods for different dependency types Source: https://github.com/stanfordnlp/corenlp/blob/main/doc/lexparser/StanfordDependenciesManual.pdf List of GrammaticalStructure methods for obtaining different dependency representations: basic, nonCollapsed, collapsed, CCPropagated, and tree. ```java basic gs.typedDependencies() nonCollapsed gs.allTypedDependencies() collapsed gs.typedDependenciesCollapsed(true) CCPropagated gs.typedDependenciesCCprocessed() tree gs.typedDependenciesCollapsedTree() ```