Spaces:
Sleeping
Sleeping
File size: 19,312 Bytes
d916065 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 |
# Natural Language Toolkit: Interface to the Stanford Parser
#
# Copyright (C) 2001-2023 NLTK Project
# Author: Steven Xu <[email protected]>
#
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
import os
import tempfile
import warnings
from subprocess import PIPE
from nltk.internals import (
_java_options,
config_java,
find_jar_iter,
find_jars_within_path,
java,
)
from nltk.parse.api import ParserI
from nltk.parse.dependencygraph import DependencyGraph
from nltk.tree import Tree
_stanford_url = "https://nlp.stanford.edu/software/lex-parser.shtml"
class GenericStanfordParser(ParserI):
"""Interface to the Stanford Parser"""
_MODEL_JAR_PATTERN = r"stanford-parser-(\d+)(\.(\d+))+-models\.jar"
_JAR = r"stanford-parser\.jar"
_MAIN_CLASS = "edu.stanford.nlp.parser.lexparser.LexicalizedParser"
_USE_STDIN = False
_DOUBLE_SPACED_OUTPUT = False
def __init__(
self,
path_to_jar=None,
path_to_models_jar=None,
model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz",
encoding="utf8",
verbose=False,
java_options="-mx4g",
corenlp_options="",
):
# find the most recent code and model jar
stanford_jar = max(
find_jar_iter(
self._JAR,
path_to_jar,
env_vars=("STANFORD_PARSER", "STANFORD_CORENLP"),
searchpath=(),
url=_stanford_url,
verbose=verbose,
is_regex=True,
),
key=lambda model_path: os.path.dirname(model_path),
)
model_jar = max(
find_jar_iter(
self._MODEL_JAR_PATTERN,
path_to_models_jar,
env_vars=("STANFORD_MODELS", "STANFORD_CORENLP"),
searchpath=(),
url=_stanford_url,
verbose=verbose,
is_regex=True,
),
key=lambda model_path: os.path.dirname(model_path),
)
# self._classpath = (stanford_jar, model_jar)
# Adding logging jar files to classpath
stanford_dir = os.path.split(stanford_jar)[0]
self._classpath = tuple([model_jar] + find_jars_within_path(stanford_dir))
self.model_path = model_path
self._encoding = encoding
self.corenlp_options = corenlp_options
self.java_options = java_options
def _parse_trees_output(self, output_):
res = []
cur_lines = []
cur_trees = []
blank = False
for line in output_.splitlines(False):
if line == "":
if blank:
res.append(iter(cur_trees))
cur_trees = []
blank = False
elif self._DOUBLE_SPACED_OUTPUT:
cur_trees.append(self._make_tree("\n".join(cur_lines)))
cur_lines = []
blank = True
else:
res.append(iter([self._make_tree("\n".join(cur_lines))]))
cur_lines = []
else:
cur_lines.append(line)
blank = False
return iter(res)
def parse_sents(self, sentences, verbose=False):
"""
Use StanfordParser to parse multiple sentences. Takes multiple sentences as a
list where each sentence is a list of words.
Each sentence will be automatically tagged with this StanfordParser instance's
tagger.
If whitespaces exists inside a token, then the token will be treated as
separate tokens.
:param sentences: Input sentences to parse
:type sentences: list(list(str))
:rtype: iter(iter(Tree))
"""
cmd = [
self._MAIN_CLASS,
"-model",
self.model_path,
"-sentences",
"newline",
"-outputFormat",
self._OUTPUT_FORMAT,
"-tokenized",
"-escaper",
"edu.stanford.nlp.process.PTBEscapingProcessor",
]
return self._parse_trees_output(
self._execute(
cmd, "\n".join(" ".join(sentence) for sentence in sentences), verbose
)
)
def raw_parse(self, sentence, verbose=False):
"""
Use StanfordParser to parse a sentence. Takes a sentence as a string;
before parsing, it will be automatically tokenized and tagged by
the Stanford Parser.
:param sentence: Input sentence to parse
:type sentence: str
:rtype: iter(Tree)
"""
return next(self.raw_parse_sents([sentence], verbose))
def raw_parse_sents(self, sentences, verbose=False):
"""
Use StanfordParser to parse multiple sentences. Takes multiple sentences as a
list of strings.
Each sentence will be automatically tokenized and tagged by the Stanford Parser.
:param sentences: Input sentences to parse
:type sentences: list(str)
:rtype: iter(iter(Tree))
"""
cmd = [
self._MAIN_CLASS,
"-model",
self.model_path,
"-sentences",
"newline",
"-outputFormat",
self._OUTPUT_FORMAT,
]
return self._parse_trees_output(
self._execute(cmd, "\n".join(sentences), verbose)
)
def tagged_parse(self, sentence, verbose=False):
"""
Use StanfordParser to parse a sentence. Takes a sentence as a list of
(word, tag) tuples; the sentence must have already been tokenized and
tagged.
:param sentence: Input sentence to parse
:type sentence: list(tuple(str, str))
:rtype: iter(Tree)
"""
return next(self.tagged_parse_sents([sentence], verbose))
def tagged_parse_sents(self, sentences, verbose=False):
"""
Use StanfordParser to parse multiple sentences. Takes multiple sentences
where each sentence is a list of (word, tag) tuples.
The sentences must have already been tokenized and tagged.
:param sentences: Input sentences to parse
:type sentences: list(list(tuple(str, str)))
:rtype: iter(iter(Tree))
"""
tag_separator = "/"
cmd = [
self._MAIN_CLASS,
"-model",
self.model_path,
"-sentences",
"newline",
"-outputFormat",
self._OUTPUT_FORMAT,
"-tokenized",
"-tagSeparator",
tag_separator,
"-tokenizerFactory",
"edu.stanford.nlp.process.WhitespaceTokenizer",
"-tokenizerMethod",
"newCoreLabelTokenizerFactory",
]
# We don't need to escape slashes as "splitting is done on the last instance of the character in the token"
return self._parse_trees_output(
self._execute(
cmd,
"\n".join(
" ".join(tag_separator.join(tagged) for tagged in sentence)
for sentence in sentences
),
verbose,
)
)
def _execute(self, cmd, input_, verbose=False):
encoding = self._encoding
cmd.extend(["-encoding", encoding])
if self.corenlp_options:
cmd.extend(self.corenlp_options.split())
default_options = " ".join(_java_options)
# Configure java.
config_java(options=self.java_options, verbose=verbose)
# Windows is incompatible with NamedTemporaryFile() without passing in delete=False.
with tempfile.NamedTemporaryFile(mode="wb", delete=False) as input_file:
# Write the actual sentences to the temporary input file
if isinstance(input_, str) and encoding:
input_ = input_.encode(encoding)
input_file.write(input_)
input_file.flush()
# Run the tagger and get the output.
if self._USE_STDIN:
input_file.seek(0)
stdout, stderr = java(
cmd,
classpath=self._classpath,
stdin=input_file,
stdout=PIPE,
stderr=PIPE,
)
else:
cmd.append(input_file.name)
stdout, stderr = java(
cmd, classpath=self._classpath, stdout=PIPE, stderr=PIPE
)
stdout = stdout.replace(b"\xc2\xa0", b" ")
stdout = stdout.replace(b"\x00\xa0", b" ")
stdout = stdout.decode(encoding)
os.unlink(input_file.name)
# Return java configurations to their default values.
config_java(options=default_options, verbose=False)
return stdout
class StanfordParser(GenericStanfordParser):
"""
>>> parser=StanfordParser(
... model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz"
... ) # doctest: +SKIP
>>> list(parser.raw_parse("the quick brown fox jumps over the lazy dog")) # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('ROOT', [Tree('NP', [Tree('NP', [Tree('DT', ['the']), Tree('JJ', ['quick']), Tree('JJ', ['brown']),
Tree('NN', ['fox'])]), Tree('NP', [Tree('NP', [Tree('NNS', ['jumps'])]), Tree('PP', [Tree('IN', ['over']),
Tree('NP', [Tree('DT', ['the']), Tree('JJ', ['lazy']), Tree('NN', ['dog'])])])])])])]
>>> sum([list(dep_graphs) for dep_graphs in parser.raw_parse_sents((
... "the quick brown fox jumps over the lazy dog",
... "the quick grey wolf jumps over the lazy fox"
... ))], []) # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('ROOT', [Tree('NP', [Tree('NP', [Tree('DT', ['the']), Tree('JJ', ['quick']), Tree('JJ', ['brown']),
Tree('NN', ['fox'])]), Tree('NP', [Tree('NP', [Tree('NNS', ['jumps'])]), Tree('PP', [Tree('IN', ['over']),
Tree('NP', [Tree('DT', ['the']), Tree('JJ', ['lazy']), Tree('NN', ['dog'])])])])])]), Tree('ROOT', [Tree('NP',
[Tree('NP', [Tree('DT', ['the']), Tree('JJ', ['quick']), Tree('JJ', ['grey']), Tree('NN', ['wolf'])]), Tree('NP',
[Tree('NP', [Tree('NNS', ['jumps'])]), Tree('PP', [Tree('IN', ['over']), Tree('NP', [Tree('DT', ['the']),
Tree('JJ', ['lazy']), Tree('NN', ['fox'])])])])])])]
>>> sum([list(dep_graphs) for dep_graphs in parser.parse_sents((
... "I 'm a dog".split(),
... "This is my friends ' cat ( the tabby )".split(),
... ))], []) # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('ROOT', [Tree('S', [Tree('NP', [Tree('PRP', ['I'])]), Tree('VP', [Tree('VBP', ["'m"]),
Tree('NP', [Tree('DT', ['a']), Tree('NN', ['dog'])])])])]), Tree('ROOT', [Tree('S', [Tree('NP',
[Tree('DT', ['This'])]), Tree('VP', [Tree('VBZ', ['is']), Tree('NP', [Tree('NP', [Tree('NP', [Tree('PRP$', ['my']),
Tree('NNS', ['friends']), Tree('POS', ["'"])]), Tree('NN', ['cat'])]), Tree('PRN', [Tree('-LRB-', [Tree('', []),
Tree('NP', [Tree('DT', ['the']), Tree('NN', ['tabby'])]), Tree('-RRB-', [])])])])])])])]
>>> sum([list(dep_graphs) for dep_graphs in parser.tagged_parse_sents((
... (
... ("The", "DT"),
... ("quick", "JJ"),
... ("brown", "JJ"),
... ("fox", "NN"),
... ("jumped", "VBD"),
... ("over", "IN"),
... ("the", "DT"),
... ("lazy", "JJ"),
... ("dog", "NN"),
... (".", "."),
... ),
... ))],[]) # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('ROOT', [Tree('S', [Tree('NP', [Tree('DT', ['The']), Tree('JJ', ['quick']), Tree('JJ', ['brown']),
Tree('NN', ['fox'])]), Tree('VP', [Tree('VBD', ['jumped']), Tree('PP', [Tree('IN', ['over']), Tree('NP',
[Tree('DT', ['the']), Tree('JJ', ['lazy']), Tree('NN', ['dog'])])])]), Tree('.', ['.'])])])]
"""
_OUTPUT_FORMAT = "penn"
def __init__(self, *args, **kwargs):
warnings.warn(
"The StanfordParser will be deprecated\n"
"Please use \033[91mnltk.parse.corenlp.CoreNLPParser\033[0m instead.",
DeprecationWarning,
stacklevel=2,
)
super().__init__(*args, **kwargs)
def _make_tree(self, result):
return Tree.fromstring(result)
class StanfordDependencyParser(GenericStanfordParser):
"""
>>> dep_parser=StanfordDependencyParser(
... model_path="edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz"
... ) # doctest: +SKIP
>>> [parse.tree() for parse in dep_parser.raw_parse("The quick brown fox jumps over the lazy dog.")] # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('jumps', [Tree('fox', ['The', 'quick', 'brown']), Tree('dog', ['over', 'the', 'lazy'])])]
>>> [list(parse.triples()) for parse in dep_parser.raw_parse("The quick brown fox jumps over the lazy dog.")] # doctest: +NORMALIZE_WHITESPACE +SKIP
[[((u'jumps', u'VBZ'), u'nsubj', (u'fox', u'NN')), ((u'fox', u'NN'), u'det', (u'The', u'DT')),
((u'fox', u'NN'), u'amod', (u'quick', u'JJ')), ((u'fox', u'NN'), u'amod', (u'brown', u'JJ')),
((u'jumps', u'VBZ'), u'nmod', (u'dog', u'NN')), ((u'dog', u'NN'), u'case', (u'over', u'IN')),
((u'dog', u'NN'), u'det', (u'the', u'DT')), ((u'dog', u'NN'), u'amod', (u'lazy', u'JJ'))]]
>>> sum([[parse.tree() for parse in dep_graphs] for dep_graphs in dep_parser.raw_parse_sents((
... "The quick brown fox jumps over the lazy dog.",
... "The quick grey wolf jumps over the lazy fox."
... ))], []) # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('jumps', [Tree('fox', ['The', 'quick', 'brown']), Tree('dog', ['over', 'the', 'lazy'])]),
Tree('jumps', [Tree('wolf', ['The', 'quick', 'grey']), Tree('fox', ['over', 'the', 'lazy'])])]
>>> sum([[parse.tree() for parse in dep_graphs] for dep_graphs in dep_parser.parse_sents((
... "I 'm a dog".split(),
... "This is my friends ' cat ( the tabby )".split(),
... ))], []) # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('dog', ['I', "'m", 'a']), Tree('cat', ['This', 'is', Tree('friends', ['my', "'"]), Tree('tabby', ['the'])])]
>>> sum([[list(parse.triples()) for parse in dep_graphs] for dep_graphs in dep_parser.tagged_parse_sents((
... (
... ("The", "DT"),
... ("quick", "JJ"),
... ("brown", "JJ"),
... ("fox", "NN"),
... ("jumped", "VBD"),
... ("over", "IN"),
... ("the", "DT"),
... ("lazy", "JJ"),
... ("dog", "NN"),
... (".", "."),
... ),
... ))],[]) # doctest: +NORMALIZE_WHITESPACE +SKIP
[[((u'jumped', u'VBD'), u'nsubj', (u'fox', u'NN')), ((u'fox', u'NN'), u'det', (u'The', u'DT')),
((u'fox', u'NN'), u'amod', (u'quick', u'JJ')), ((u'fox', u'NN'), u'amod', (u'brown', u'JJ')),
((u'jumped', u'VBD'), u'nmod', (u'dog', u'NN')), ((u'dog', u'NN'), u'case', (u'over', u'IN')),
((u'dog', u'NN'), u'det', (u'the', u'DT')), ((u'dog', u'NN'), u'amod', (u'lazy', u'JJ'))]]
"""
_OUTPUT_FORMAT = "conll2007"
def __init__(self, *args, **kwargs):
warnings.warn(
"The StanfordDependencyParser will be deprecated\n"
"Please use \033[91mnltk.parse.corenlp.CoreNLPDependencyParser\033[0m instead.",
DeprecationWarning,
stacklevel=2,
)
super().__init__(*args, **kwargs)
def _make_tree(self, result):
return DependencyGraph(result, top_relation_label="root")
class StanfordNeuralDependencyParser(GenericStanfordParser):
"""
>>> from nltk.parse.stanford import StanfordNeuralDependencyParser # doctest: +SKIP
>>> dep_parser=StanfordNeuralDependencyParser(java_options='-mx4g')# doctest: +SKIP
>>> [parse.tree() for parse in dep_parser.raw_parse("The quick brown fox jumps over the lazy dog.")] # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('jumps', [Tree('fox', ['The', 'quick', 'brown']), Tree('dog', ['over', 'the', 'lazy']), '.'])]
>>> [list(parse.triples()) for parse in dep_parser.raw_parse("The quick brown fox jumps over the lazy dog.")] # doctest: +NORMALIZE_WHITESPACE +SKIP
[[((u'jumps', u'VBZ'), u'nsubj', (u'fox', u'NN')), ((u'fox', u'NN'), u'det',
(u'The', u'DT')), ((u'fox', u'NN'), u'amod', (u'quick', u'JJ')), ((u'fox', u'NN'),
u'amod', (u'brown', u'JJ')), ((u'jumps', u'VBZ'), u'nmod', (u'dog', u'NN')),
((u'dog', u'NN'), u'case', (u'over', u'IN')), ((u'dog', u'NN'), u'det',
(u'the', u'DT')), ((u'dog', u'NN'), u'amod', (u'lazy', u'JJ')), ((u'jumps', u'VBZ'),
u'punct', (u'.', u'.'))]]
>>> sum([[parse.tree() for parse in dep_graphs] for dep_graphs in dep_parser.raw_parse_sents((
... "The quick brown fox jumps over the lazy dog.",
... "The quick grey wolf jumps over the lazy fox."
... ))], []) # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('jumps', [Tree('fox', ['The', 'quick', 'brown']), Tree('dog', ['over',
'the', 'lazy']), '.']), Tree('jumps', [Tree('wolf', ['The', 'quick', 'grey']),
Tree('fox', ['over', 'the', 'lazy']), '.'])]
>>> sum([[parse.tree() for parse in dep_graphs] for dep_graphs in dep_parser.parse_sents((
... "I 'm a dog".split(),
... "This is my friends ' cat ( the tabby )".split(),
... ))], []) # doctest: +NORMALIZE_WHITESPACE +SKIP
[Tree('dog', ['I', "'m", 'a']), Tree('cat', ['This', 'is', Tree('friends',
['my', "'"]), Tree('tabby', ['-LRB-', 'the', '-RRB-'])])]
"""
_OUTPUT_FORMAT = "conll"
_MAIN_CLASS = "edu.stanford.nlp.pipeline.StanfordCoreNLP"
_JAR = r"stanford-corenlp-(\d+)(\.(\d+))+\.jar"
_MODEL_JAR_PATTERN = r"stanford-corenlp-(\d+)(\.(\d+))+-models\.jar"
_USE_STDIN = True
_DOUBLE_SPACED_OUTPUT = True
def __init__(self, *args, **kwargs):
warnings.warn(
"The StanfordNeuralDependencyParser will be deprecated\n"
"Please use \033[91mnltk.parse.corenlp.CoreNLPDependencyParser\033[0m instead.",
DeprecationWarning,
stacklevel=2,
)
super().__init__(*args, **kwargs)
self.corenlp_options += "-annotators tokenize,ssplit,pos,depparse"
def tagged_parse_sents(self, sentences, verbose=False):
"""
Currently unimplemented because the neural dependency parser (and
the StanfordCoreNLP pipeline class) doesn't support passing in pre-
tagged tokens.
"""
raise NotImplementedError(
"tagged_parse[_sents] is not supported by "
"StanfordNeuralDependencyParser; use "
"parse[_sents] or raw_parse[_sents] instead."
)
def _make_tree(self, result):
return DependencyGraph(result, top_relation_label="ROOT")
|