| Title: | Wrapper to the 'spaCy' 'NLP' Library |
|---|---|
| Description: | An R wrapper to the 'Python' 'spaCy' 'NLP' library, from <https://spacy.io>. |
| Authors: | Kenneth Benoit [cre, aut, cph] (ORCID: <https://orcid.org/0000-0002-0797-564X>), Akitaka Matsuo [aut] (ORCID: <https://orcid.org/0000-0002-3323-6330>), Johannes Gruber [ctb] (ORCID: <https://orcid.org/0000-0001-9177-1772>), European Research Council [fnd] (ERC-2011-StG 283794-QUANTESS) |
| Maintainer: | Kenneth Benoit <[email protected]> |
| License: | GPL-3 |
| Version: | 1.4.0.9000 |
| Built: | 2026-12-01 04:37:42 UTC |
| Source: | https://github.com/quanteda/spacyr |
An R wrapper to the Python (Cython) spaCy NLP system, from https://spacy.io. Nicely integrated with quanteda. spacyr is designed to provide easy access to the powerful functionality of spaCy, in a simple format.
Ken Benoit and Akitaka Matsuo
https://spacy.io, https://spacyr.quanteda.io.
Useful links:
Turn phrases, spaCy-style pattern lists or a data.frame of patterns into a
spacyr_entity_patterns object: a checked set of rules for spaCy's
entity_ruler, which finds named entities by matching phrases or sequences
of tokens. Creating the object needs neither Python nor spaCy; pass it to
spacy_initialize() as entity_patterns to add the rules to the pipeline.
as_entity_patterns(x, ...) ## S3 method for class 'character' as_entity_patterns( x, label = NULL, id = NULL, case_insensitive = FALSE, valuetype = c("fixed", "glob", "regex"), ... ) ## S3 method for class 'list' as_entity_patterns(x, case_insensitive = FALSE, ...) ## S3 method for class 'data.frame' as_entity_patterns(x, case_insensitive = FALSE, concatenator = NULL, ...) ## S3 method for class 'dictionary2' as_entity_patterns( x, case_insensitive = TRUE, valuetype = c("glob", "regex", "fixed"), levels = 1, ... )as_entity_patterns(x, ...) ## S3 method for class 'character' as_entity_patterns( x, label = NULL, id = NULL, case_insensitive = FALSE, valuetype = c("fixed", "glob", "regex"), ... ) ## S3 method for class 'list' as_entity_patterns(x, case_insensitive = FALSE, ...) ## S3 method for class 'data.frame' as_entity_patterns(x, case_insensitive = FALSE, concatenator = NULL, ...) ## S3 method for class 'dictionary2' as_entity_patterns( x, case_insensitive = TRUE, valuetype = c("glob", "regex", "fixed"), levels = 1, ... )
x |
the patterns to convert:
|
... |
not used. |
label |
character; the entity label of each phrase, such as |
id |
character; an optional ID for each phrase, either one for all
phrases or one per phrase. spaCy gives the ID of the pattern that matched
as each entity's |
case_insensitive |
logical; if |
valuetype |
how phrases and the values of a dictionary are read:
|
concatenator |
for the output of |
levels |
for a dictionary, the levels of its keys that become
labels, as in
|
Token patterns are checked for their structure only: that each is a list with one named list per token. spaCy checks the attribute names, operators and values when the patterns are added to a pipeline, and reports any errors then.
Two conversions make patterns from R reach spaCy in the form it expects.
The values of spaCy's set operators (IN, NOT_IN, IS_SUBSET,
IS_SUPERSET and INTERSECTS) are always stored as lists, so that
list(LOWER = list(IN = "dr")) stays a list of one value, rather than
becoming a single string. Whole numbers stored as doubles, such as 3
in list(LENGTH = 3), become integers, since spaCy does not accept
decimal numbers in token patterns.
Phrases, including dictionary values without wildcards, are split into
tokens by the pipeline's own tokenizer, and some of its rules depend on
case: spaCy's English models keep "Inc." as one token, but split
"inc." into "inc" and ".". So write phrases in their usual case, even with
case_insensitive = TRUE, and make dictionaries with
quanteda::dictionary(tolower = FALSE), since by default it lowercases
their values.
With case_insensitive = TRUE, the parts of a phrase or dictionary value
that has a wildcard are put in lower case by R when the patterns are
made, since making them does not need spaCy, while spaCy compares them
with its own lower case form of each token. The two differ for a few
characters, such as the dotted capital I of Turkish, and a value with
such a character and a wildcard may then not match. This holds wherever
the patterns are used, in spacy_initialize() or in spacy_match().
Given the character vector or the dictionary itself, and not patterns
made from it, spacy_match() lowercases with spaCy and does not have
this limit.
Patterns match spaCy's tokens, not characters. For instance, spaCy's
English models make "Prof." a single token, so a pattern for academic
titles needs to list both "prof" and "prof.", to match titles written
with and without a full stop.
A spacyr_entity_patterns object: a data.frame with one row per
pattern and the columns
label the entity label;
pattern a list column, holding for each pattern a single phrase or a
list of token patterns;
id the pattern's ID, or NA;
case_insensitive for phrases, whether they match regardless of case;
NA for token patterns.
Duplicated patterns are removed.
entity_patterns_read() and entity_patterns_write() to read
and write patterns as files, spacy_initialize() to use them, and
as.dictionary.spacyr_entity_patterns() to make a quanteda
dictionary of patterns that are all phrases
# phrases, labelled by their names or by `label` as_entity_patterns(c(ORG = "Acme Widgets", GPE = "San Francisco")) as_entity_patterns(c("Acme Widgets", "Globex"), label = "ORG") # phrases with wildcards, in any case as_entity_patterns(c(ORG = "acme*", ORG = "globex corp*"), valuetype = "glob", case_insensitive = TRUE) # a token pattern for people with academic titles: a title, followed by # the first token of a person the model recognises (ENT_IOB "B") and the # rest of that person (ENT_IOB "I"), so that it extends one entity without # running into a person who follows it titles <- c("dr", "dr.", "prof", "prof.") as_entity_patterns(list( label = "PERSON", pattern = list(list(LOWER = list(IN = titles)), list(ENT_TYPE = "PERSON", ENT_IOB = "B"), list(ENT_TYPE = "PERSON", ENT_IOB = "I", OP = "*")) )) # a data.frame of patterns as_entity_patterns(data.frame(label = c("ORG", "ORG"), pattern = c("Acme Widgets", "Globex"))) # a quanteda dictionary, with labels from its keys if (requireNamespace("quanteda", quietly = TRUE)) { dict <- quanteda::dictionary(list(ORG = c("acme widgets", "globex*"), PERSON = "dr * who")) as_entity_patterns(dict) # labels from the first two levels of its keys nested <- quanteda::dictionary(list( place = list(us = c("new york", "boston"), uk = "london"))) as_entity_patterns(nested) as_entity_patterns(nested, levels = 1:2) } # entities found by spaCy, to use as rules for other texts ## Not run: spacy_initialize() found <- spacy_extract_entity("Acme Widgets hired Jane Smith.") as_entity_patterns(found) spacy_finalize() ## End(Not run) # combine sets of patterns c(as_entity_patterns(c(ORG = "Globex")), as_entity_patterns(c(PERSON = "Jane Smith")))# phrases, labelled by their names or by `label` as_entity_patterns(c(ORG = "Acme Widgets", GPE = "San Francisco")) as_entity_patterns(c("Acme Widgets", "Globex"), label = "ORG") # phrases with wildcards, in any case as_entity_patterns(c(ORG = "acme*", ORG = "globex corp*"), valuetype = "glob", case_insensitive = TRUE) # a token pattern for people with academic titles: a title, followed by # the first token of a person the model recognises (ENT_IOB "B") and the # rest of that person (ENT_IOB "I"), so that it extends one entity without # running into a person who follows it titles <- c("dr", "dr.", "prof", "prof.") as_entity_patterns(list( label = "PERSON", pattern = list(list(LOWER = list(IN = titles)), list(ENT_TYPE = "PERSON", ENT_IOB = "B"), list(ENT_TYPE = "PERSON", ENT_IOB = "I", OP = "*")) )) # a data.frame of patterns as_entity_patterns(data.frame(label = c("ORG", "ORG"), pattern = c("Acme Widgets", "Globex"))) # a quanteda dictionary, with labels from its keys if (requireNamespace("quanteda", quietly = TRUE)) { dict <- quanteda::dictionary(list(ORG = c("acme widgets", "globex*"), PERSON = "dr * who")) as_entity_patterns(dict) # labels from the first two levels of its keys nested <- quanteda::dictionary(list( place = list(us = c("new york", "boston"), uk = "london"))) as_entity_patterns(nested) as_entity_patterns(nested, levels = 1:2) } # entities found by spaCy, to use as rules for other texts ## Not run: spacy_initialize() found <- spacy_extract_entity("Acme Widgets hired Jane Smith.") as_entity_patterns(found) spacy_finalize() ## End(Not run) # combine sets of patterns c(as_entity_patterns(c(ORG = "Globex")), as_entity_patterns(c(PERSON = "Jane Smith")))
Turn the positions that spacy_match(), spacy_extract_entity() or
spacy_extract_nounphrases() return into an index of quanteda, as
quanteda::index() makes, so that quanteda::kwic() can show each of them
in its context. Making the index needs neither quanteda nor spaCy.
as_index(x)as_index(x)
x |
the output of |
The positions count spaCy's tokens from 1 in each document, with its
tokens of whitespace. They are the positions in
quanteda::as.tokens(spacy_parse(x)) for the same texts and the same
pipeline, and not those in quanteda::tokens(x), which are
quanteda's tokens, or in the output of spacy_tokenize(), which by
default leaves out whitespace. So give quanteda::kwic() the tokens of
spacy_parse(), as in the examples. quanteda::kwic() does not check
that an index was made from the tokens it is given: with other tokens, it
shows whatever is at those positions.
spacy_parse() needs the sentences of each document, which come from the
parser of the language model or from a sentence segmenter. In a pipeline
that sets no sentence boundaries, spacy_match() still returns the
positions of its matches, but spacy_parse() fails, and so cannot give
the tokens for a concordance.
quanteda keeps the names of documents in Unicode's composed form
(NFC), so that an "e" followed by a combining accent becomes the single
accented character. as_index() does the same to doc_id when the
stringi package is installed, which quanteda needs: the
matches of a document whose name is not in that form then keep their
place in the concordance, which would otherwise drop them without a
message. Giving the same quanteda::corpus() to spacy_match() and to
spacy_parse() has the same effect, since the names in a corpus are
already in that form.
A match of a dependency pattern has one row for each of its nodes, and so
one row in the index for each node, also when two nodes are the same
token. quanteda::kwic() keeps the rows of the index in their order, and
drops those of documents that the tokens do not have. When the tokens
have every document, row i of the concordance is row i of x, so the
other columns of x, such as match_id and node, can be added to it.
The concordance shows the matches that it is given. Which matches
spacy_match() returns where they overlap is set by its overlap, whose
rule is not that of quanteda::kwic(x, pattern), as the details of
spacy_match() describe. A concordance of matches keeps a "New York"
inside another label's "New York Times", for instance, which
quanteda's own search for the two would drop.
An object of class index, as quanteda::index() returns: a
data.frame with one row for each row of x, in the same order, and the
columns
docname the document, from doc_id, in Unicode's composed form
(NFC), as the details describe;
from and to the positions of the first and last token, from
start_id and length;
pattern a factor: the label of a match, the ent_type of an
entity, or "nounphrase" for a noun phrase.
spacy_match(), spacy_extract_entity(),
spacy_extract_nounphrases(), quanteda::kwic()
# an index needs no spaCy: here, of matches written by hand m <- data.frame(doc_id = c("d1", "d1"), label = c("city", "paper"), start_id = c(2, 2), length = c(2, 3)) as_index(m) as_index(NULL) ## Not run: spacy_initialize() txt <- c(d1 = "The New York Times is a paper in New York.", d2 = "Jane Smith wrote the book in Boston.") toks <- quanteda::as.tokens(spacy_parse(txt)) # matches in context m <- spacy_match(txt, quanteda::phrase(c("new york", "the book"))) quanteda::kwic(toks, index = as_index(m), window = 3) # entities and noun phrases quanteda::kwic(toks, index = as_index(spacy_extract_entity(txt)), window = 3) quanteda::kwic(toks, index = as_index(spacy_extract_nounphrases(txt)), window = 3) spacy_finalize() ## End(Not run)# an index needs no spaCy: here, of matches written by hand m <- data.frame(doc_id = c("d1", "d1"), label = c("city", "paper"), start_id = c(2, 2), length = c(2, 3)) as_index(m) as_index(NULL) ## Not run: spacy_initialize() txt <- c(d1 = "The New York Times is a paper in New York.", d2 = "Jane Smith wrote the book in Boston.") toks <- quanteda::as.tokens(spacy_parse(txt)) # matches in context m <- spacy_match(txt, quanteda::phrase(c("new york", "the book"))) quanteda::kwic(toks, index = as_index(m), window = 3) # entities and noun phrases quanteda::kwic(toks, index = as_index(spacy_extract_entity(txt)), window = 3) quanteda::kwic(toks, index = as_index(spacy_extract_nounphrases(txt)), window = 3) spacy_finalize() ## End(Not run)
A method of quanteda::as.dictionary() for the entity patterns that
as_entity_patterns() makes, when all of them are phrases: each label
becomes a key, and the phrases with that label become its values. It needs
the quanteda package, and is available when quanteda is
loaded.
## S3 method for class 'spacyr_entity_patterns' as.dictionary(x, ...)## S3 method for class 'spacyr_entity_patterns' as.dictionary(x, ...)
x |
a |
... |
not used; any argument given here is an error |
A dictionary holds words and phrases, so x can hold only phrases. Token
patterns have no counterpart in a dictionary: when x has any, the
conversion stops with an error that names their labels.
A dictionary has less than the entity patterns have, so the conversion keeps the different pairs of a label and a phrase, and nothing else:
The id of a pattern is dropped.
So is case_insensitive. A dictionary does not say how its values are
matched: that is set where it is used, as by case_insensitive in
quanteda::tokens_lookup() or in as_entity_patterns().
quanteda::dictionary() removes the whitespace at the start and the end
of a value, and a phrase that occurs more than once under a label is
kept once.
The values are grouped by key, so their order is not the order of the patterns when the patterns of a label are not next to each other.
quanteda reads * and ? in a dictionary value as wildcards, since
its default is valuetype = "glob", while in a phrase of an entity
pattern they are those characters themselves. The conversion gives a
warning when a phrase has one. To match such values as they are written,
use valuetype = "fixed", as in
quanteda::tokens_lookup(x, dictionary, valuetype = "fixed").
An object with no patterns gives a dictionary with no keys, which
as_entity_patterns() makes into no patterns again. quanteda takes
such a dictionary in quanteda::kwic() and quanteda::dfm_lookup(), but
quanteda::tokens_lookup() stops with an error for it (in
quanteda 4.5.1), so check length() of the dictionary first where
it can be empty.
To make entity patterns of the dictionary again, with the phrases as they
are written and matched in their own case, use
as_entity_patterns(d, valuetype = "fixed", case_insensitive = FALSE).
Without those arguments, as_entity_patterns() reads the values of a
dictionary as quanteda does: as globs, matched in any case.
A quanteda dictionary with one key for each label of x, in
the order in which the labels first occur. Its values are the different
phrases with that label, in the case in which they are written.
as_entity_patterns(), quanteda::dictionary(),
quanteda::tokens_lookup()
pat <- as_entity_patterns(c(ORG = "Acme Widgets", ORG = "Globex", GPE = "New York")) d <- quanteda::as.dictionary(pat) d # and back, as phrases matched in their own case as_entity_patterns(d, valuetype = "fixed", case_insensitive = FALSE)pat <- as_entity_patterns(c(ORG = "Acme Widgets", ORG = "Globex", GPE = "New York")) d <- quanteda::as.dictionary(pat) d # and back, as phrases matched in their own case as_entity_patterns(d, valuetype = "fixed", case_insensitive = FALSE)
A sample of text from the Irish budget debate of 2010 (531 tokens long).
data_char_paragraphdata_char_paragraph
An object of class character of length 1.
A character object consisting of 30 short documents in plain text format for testing. Each document is one or two brief sentences.
data_char_sentencesdata_char_sentences
An object of class character of length 30.
From an object parsed by spacy_parse(), extract the entities as a
separate object, or convert the multi-word entities into single "token"
consisting of the concatenated elements of the multi-word entities.
entity_extract(x, type = c("named", "extended", "all"), concatenator = "_") entity_consolidate(x, concatenator = "_")entity_extract(x, type = c("named", "extended", "all"), concatenator = "_") entity_consolidate(x, concatenator = "_")
x |
output from |
type |
type of named entities, either |
concatenator |
the character(s) used to join the elements of multi-word named entities |
entity_extract() returns a data.frame of all named
entities, containing the following fields:
doc_id name of the document containing the entity
sentence_id the sentence ID containing the entity, within the document
entity the named entity
entity_type the type of named entities (e.g. PERSON, ORG, PERCENT, etc.)
entity_consolidate returns a modified data.frame of
parsed results, where the named entities have been combined into a single
"token". Currently, dependency parsing is removed when this consolidation
occurs. If x has the columns start and end of
spacy_parse(offsets = TRUE), a consolidated entity runs from the start
of its first token to the end of its last.
## Not run: spacy_initialize() # entity extraction txt <- "Mr. Smith of moved to San Francisco in December." parsed <- spacy_parse(txt, entity = TRUE) entity_extract(parsed) entity_extract(parsed, type = "all") ## End(Not run) ## Not run: # consolidating multi-word entities txt <- "The House of Representatives voted to suspend aid to South Dakota." parsed <- spacy_parse(txt, entity = TRUE) entity_consolidate(parsed) ## End(Not run)## Not run: spacy_initialize() # entity extraction txt <- "Mr. Smith of moved to San Francisco in December." parsed <- spacy_parse(txt, entity = TRUE) entity_extract(parsed) entity_extract(parsed, type = "all") ## End(Not run) ## Not run: # consolidating multi-word entities txt <- "The House of Representatives voted to suspend aid to South Dakota." parsed <- spacy_parse(txt, entity = TRUE) entity_consolidate(parsed) ## End(Not run)
Read entity patterns from a file, or write them to one, for instance to keep them with a project, edit them by hand, or share them with users of spaCy in Python.
entity_patterns_read(file, label = NULL, case_insensitive = FALSE) entity_patterns_write(x, file)entity_patterns_read(file, label = NULL, case_insensitive = FALSE) entity_patterns_write(x, file)
file |
the path of the file to read or write. Its extension sets the
format, and must be
|
label |
character; for a |
case_insensitive |
logical; for phrases, whether they match regardless
of case. See |
x |
patterns to write: a |
Reading and writing JSON needs the jsonlite package.
entity_patterns_write() writes JSONL only, so file must end in .jsonl.
It checks the patterns before opening file, so an existing file is left
as it was if they are not valid. A phrase that matches regardless of case is written with the extra
key "case_insensitive": true, which entity_patterns_read() reads back.
spaCy itself ignores that key, and matches the phrase exactly.
Patterns written and read back are identical to the originals.
entity_patterns_read() returns a spacyr_entity_patterns
object. entity_patterns_write() returns file, invisibly.
if (requireNamespace("jsonlite", quietly = TRUE)) { pats <- as_entity_patterns(list( list(label = "PERSON", pattern = list(list(LOWER = list(IN = c("dr", "dr."))), list(ENT_TYPE = "PERSON", ENT_IOB = "B"), list(ENT_TYPE = "PERSON", ENT_IOB = "I", OP = "*"))), list(label = "ORG", pattern = "Acme Widgets", id = "acme") )) file <- tempfile(fileext = ".jsonl") entity_patterns_write(pats, file) readLines(file) identical(entity_patterns_read(file), pats) }if (requireNamespace("jsonlite", quietly = TRUE)) { pats <- as_entity_patterns(list( list(label = "PERSON", pattern = list(list(LOWER = list(IN = c("dr", "dr."))), list(ENT_TYPE = "PERSON", ENT_IOB = "B"), list(ENT_TYPE = "PERSON", ENT_IOB = "I", OP = "*"))), list(label = "ORG", pattern = "Acme Widgets", id = "acme") )) file <- tempfile(fileext = ".jsonl") entity_patterns_write(pats, file) readLines(file) identical(entity_patterns_read(file), pats) }
Shows documents parsed by spacy_parse() with their named entities
highlighted and labelled, as HTML made by displaCy, spaCy's visualizer
(see https://spacy.io/usage/visualizers#ent).
entity_visualize(x, entities = NULL, colors = NULL, view = FALSE)entity_visualize(x, entities = NULL, colors = NULL, view = FALSE)
x |
the output of |
entities |
the entity labels to highlight, as a character vector
such as |
colors |
a named character vector of colours for labels, such as
|
view |
logical; if |
The entities are those of the entity column of the parse, so
it needs entity = TRUE, the default of spacy_parse(). They include
any from rules given to spacy_initialize() as entity_patterns. The
documents are not processed again.
A parse does not keep the texts, so the text shown is made from the
tokens. With spacy_parse(x, offsets = TRUE) the tokens are spaced as
they were in the text. Otherwise there is a space between every two
tokens, also before punctuation and within words that spaCy splits,
such as did n't; the entities are the same, and a message, given
once in a session, says how to get the spacing of the text. In the
output of entity_consolidate() each entity is one token, shown with
the concatenator that joined its parts.
The documents are shown in the order of the parse, each in a block of
its own. A document without entities, or without any of the labels in
entities, is shown as plain text. The HTML is made by spaCy, which is
initialized if it has not been.
a character vector of length one, with the HTML for all the
documents. It is a fragment and not a whole page, so that it can be
put into a page, an R Markdown document or a Shiny app. It is returned
invisibly when view = TRUE, and is "" when there are no documents.
spacy_parse(); entity_extract() and spacy_extract_entity()
for the entities as data.
## Not run: spacy_initialize() txt <- head(data_char_sentences, 8) parsed <- spacy_parse(txt, offsets = TRUE) # save as HTML html <- entity_visualize(parsed) # open in the browser entity_visualize(parsed, view = TRUE) # only some labels, and a colour of one's own entity_visualize(parsed, entities = c("ORG", "GPE"), colors = c(GPE = "gold"), view = TRUE) ## End(Not run)## Not run: spacy_initialize() txt <- head(data_char_sentences, 8) parsed <- spacy_parse(txt, offsets = TRUE) # save as HTML html <- entity_visualize(parsed) # open in the browser entity_visualize(parsed, view = TRUE) # only some labels, and a colour of one's own entity_visualize(parsed, entities = c("ORG", "GPE"), colors = c(GPE = "gold"), view = TRUE) ## End(Not run)
From an object parsed by spacy_parse(), extract the multi-word
noun phrases as a separate object, or convert the multi-word noun phrases
into single "token" consisting of the concatenated elements of the multi-word
noun phrases.
nounphrase_extract(x, concatenator = "_") nounphrase_consolidate(x, concatenator = "_")nounphrase_extract(x, concatenator = "_") nounphrase_consolidate(x, concatenator = "_")
x |
output from |
concatenator |
the character(s) used to join elements of multi-word noun phrases |
noun returns a data.frame of all named
entities, containing the following fields:
doc_id name of the document containing the noun phrase
sentence_id the sentence ID containing the noun phrase, within the document
nounphrase the noun phrase
root the root token of the noun phrase
nounphrase_consolidate returns a modified data.frame of
parsed results, where the noun phrases have been combined into a single
"token". Currently, dependency parsing is removed when this consolidation
occurs. If x has the columns start and end of
spacy_parse(offsets = TRUE), a consolidated noun phrase runs from the
start of its first token to the end of its last.
## Not run: spacy_initialize() # entity extraction txt <- "Mr. Smith of moved to San Francisco in December." parsed <- spacy_parse(txt, nounphrase = TRUE) entity_extract(parsed) ## End(Not run) ## Not run: # consolidating multi-word noun phrases txt <- "The House of Representatives voted to suspend aid to South Dakota." parsed <- spacy_parse(txt, nounphrase = TRUE) nounphrase_consolidate(parsed) ## End(Not run)## Not run: spacy_initialize() # entity extraction txt <- "Mr. Smith of moved to San Francisco in December." parsed <- spacy_parse(txt, nounphrase = TRUE) entity_extract(parsed) ## End(Not run) ## Not run: # consolidating multi-word noun phrases txt <- "The House of Representatives voted to suspend aid to South Dakota." parsed <- spacy_parse(txt, nounphrase = TRUE) nounphrase_consolidate(parsed) ## End(Not run)
Methods of quanteda's functions for the output of spacy_parse():
its tokens as a quanteda tokens object, and its documents and their
sizes. They need the quanteda package, and are available when both
packages are loaded.
## S3 method for class 'spacyr_parsed' as.tokens( x, concatenator = "/", include_pos = c("none", "pos", "tag"), use_lemma = FALSE, ... ) ## S3 method for class 'spacyr_parsed' docnames(x) ## S3 method for class 'spacyr_parsed' ndoc(x) ## S3 method for class 'spacyr_parsed' ntoken(x, ...) ## S3 method for class 'spacyr_parsed' ntype(x, ...) ## S3 method for class 'spacyr_parsed' nsentence(x)## S3 method for class 'spacyr_parsed' as.tokens( x, concatenator = "/", include_pos = c("none", "pos", "tag"), use_lemma = FALSE, ... ) ## S3 method for class 'spacyr_parsed' docnames(x) ## S3 method for class 'spacyr_parsed' ndoc(x) ## S3 method for class 'spacyr_parsed' ntoken(x, ...) ## S3 method for class 'spacyr_parsed' ntype(x, ...) ## S3 method for class 'spacyr_parsed' nsentence(x)
x |
the output of |
concatenator |
the character that joins a token and its part of
speech, when |
include_pos |
which part of speech to add to each token, after
|
use_lemma |
if |
... |
not used |
The tokens are spaCy's, with its tokens of whitespace, so their positions
are those that spacy_match(), spacy_extract_entity() and
spacy_extract_nounphrases() report in start_id: see as_index().
as.tokens() returns a quanteda tokens object with the tokens of
each document, with the document variables of the corpus that was
parsed, if it was a corpus.
docnames() returns the names of the documents, and ndoc() their
number.
ntoken(), ntype() and nsentence() return the number of tokens, of
different tokens and of sentences in each document, as an integer
vector named by document, in the order of docnames().
All six methods agree on the documents of x. spacy_parse() keeps with
its output the names of all the documents it was given, in their order,
and the document variables of a quanteda corpus. So a document in
which spaCy found no tokens, such as an empty text, is a document with no
tokens here, although it has no row in x.
Taking rows out of x can leave that record as it was. It is therefore
used only as far as the rows agree with it:
When every document that had tokens still has rows, the documents are all those that were parsed. Removing some of the tokens, such as the punctuation, does not remove a document.
When a document that had tokens has no rows left, documents were taken
out of x, and the documents are those that have rows. One without
tokens is then not kept either.
When x has rows that were not parsed with the others, or has no
record, as an object saved by an earlier version of spacyr or one
that another function made into a new data.frame, the documents are
those that have rows, without document variables.
rbind() of parses combines their records when no two of them have a
document of the same name: the result has the documents of all of them,
and their document variables when all have the same ones. When two parses
have a document of the same name, the result has no record, since the
rows of the two cannot be told apart: its documents are those that have
rows, without document variables. Other ways of combining parses, such as
dplyr::bind_rows(), can keep the record of the first. It is then not
used when a document has more rows than it had tokens, or a name that the
record does not have; give the documents different names to be sure.
The documents are in the order in which they were parsed, or in the order
of the rows of x when that is another, with the documents without
tokens last.
Until spacyr 2.0 these methods were part of quanteda. To use
them on an object that was saved to a file, load spacyr as well as
quanteda, for instance with library("spacyr"): reading the object
does not load it.
spacy_parse(), as_index(), quanteda::as.tokens(),
quanteda::docnames(), quanteda::ntoken()
## Not run: spacy_initialize() corp <- quanteda::corpus(c(d1 = "And now for something different.", d2 = "", d3 = "Jack and Jill are children."), docvars = data.frame(year = 2001:2003)) parsed <- spacy_parse(corp) quanteda::docnames(parsed) quanteda::ntoken(parsed) quanteda::nsentence(parsed) toks <- quanteda::as.tokens(parsed) toks quanteda::docvars(toks) quanteda::as.tokens(parsed, include_pos = "pos") spacy_finalize() ## End(Not run)## Not run: spacy_initialize() corp <- quanteda::corpus(c(d1 = "And now for something different.", d2 = "", d3 = "Jack and Jill are children."), docvars = data.frame(year = 2001:2003)) parsed <- spacy_parse(corp) quanteda::docnames(parsed) quanteda::ntoken(parsed) quanteda::nsentence(parsed) toks <- quanteda::as.tokens(parsed) toks quanteda::docvars(toks) quanteda::as.tokens(parsed, include_pos = "pos") spacy_finalize() ## End(Not run)
Download spaCy language models
spacy_download_langmodel(lang_models = "en_core_web_sm", force = FALSE)spacy_download_langmodel(lang_models = "en_core_web_sm", force = FALSE)
lang_models |
character; language models to be installed. Defaults
|
force |
ignore if spaCy/the lang_models is already present and install it anyway. |
Models are downloaded from GitHub. If a download fails, for instance because of a temporary server error, it is tried twice more, after 10 and 30 seconds, and a warning is given if all three attempts fail.
Invisibly returns the installation log.
## Not run: # install medium sized model spacy_download_langmodel("en_core_web_md") #' # install several models with spaCy spacy_install(lang_models = c("en_core_web_sm", "de_core_news_sm")) # install transformer based model spacy_download_langmodel("en_core_web_trf") ## End(Not run)## Not run: # install medium sized model spacy_download_langmodel("en_core_web_md") #' # install several models with spaCy spacy_install(lang_models = c("en_core_web_sm", "de_core_news_sm")) # install transformer based model spacy_download_langmodel("en_core_web_trf") ## End(Not run)
Deprecated. spacyr now always uses a virtual environment,
making this function redundant.
spacy_download_langmodel_virtualenv(...)spacy_download_langmodel_virtualenv(...)
... |
not used |
This function extracts named entities from texts, based on the entity tag
ent attributes of documents objects parsed by spaCy (see
https://spacy.io/usage/linguistic-features#named-entities).
spacy_extract_entity( x, output = c("data.frame", "list"), type = c("all", "named", "extended"), multithread, n_process = 1L, batch_size = NULL, ..., offsets = FALSE )spacy_extract_entity( x, output = c("data.frame", "list"), type = c("all", "named", "extended"), multithread, n_process = 1L, batch_size = NULL, ..., offsets = FALSE )
x |
a character object or a TIF-compliant corpus data.frame (see https://github.com/ropenscilabs/tif) |
output |
type of returned object, either |
type |
type of named entities, either |
multithread |
deprecated; it no longer has any effect, and gives a
warning if supplied. Documents are always processed in
batches with spaCy's |
n_process |
the number of processes for spaCy's |
batch_size |
the number of documents that spaCy's |
... |
unused |
offsets |
logical; if |
When the option output = "data.frame" is selected, the
function returns a data.frame with the following fields, and with
start and end after them when offsets = TRUE.
textcontents of entity
ent_typetype of entity (e.g. ORG for
organizations)
start_idserial number ID of starting token:
its position in the document, starting at 1 and counting every token
of spaCy's, as the rows of spacy_parse(x) do. Whitespace tokens are
counted, so where a document has them this is not the position among
the tokens of spacy_tokenize(x) with default options, which leaves
them out.
lengthnumber
of words (tokens) included in a named entity (e.g. for an entity, "New York
Stock Exchange"", length = 4)
either a list or data.frame of tokens
The components of spaCy's pipeline that entities do not need are left out
of the call, which makes it faster: with spaCy's English models, the
tagger, the attribute ruler and the lemmatizer. The output is the same as
when every component runs, so a component stays whenever a later one
that stays may read what it sets, and nothing is left out when the
pipeline has a component that is not one of spaCy's standard ones. See
the details of spacy_parse(), and the article "Improving Performance"
on the package website.
## Not run: spacy_initialize() txt <- c(doc1 = "The Supreme Court is located in Washington D.C.", doc2 = "Paul earned a postgraduate degree from MIT.") spacy_extract_entity(txt) spacy_extract_entity(txt, output = "list") ## End(Not run)## Not run: spacy_initialize() txt <- c(doc1 = "The Supreme Court is located in Washington D.C.", doc2 = "Paul earned a postgraduate degree from MIT.") spacy_extract_entity(txt) spacy_extract_entity(txt, output = "list") ## End(Not run)
This function extracts noun phrases from documents, based on the
noun_chunks attributes of documents objects parsed by spaCy (see
https://spacy.io/usage/linguistic-features#noun-chunks).
spacy_extract_nounphrases( x, output = c("data.frame", "list"), multithread, n_process = 1L, batch_size = NULL, ..., offsets = FALSE )spacy_extract_nounphrases( x, output = c("data.frame", "list"), multithread, n_process = 1L, batch_size = NULL, ..., offsets = FALSE )
x |
a character object or a TIF-compliant corpus data.frame (see https://github.com/ropenscilabs/tif) |
output |
type of returned object, either |
multithread |
deprecated; it no longer has any effect, and gives a
warning if supplied. Documents are always processed in
batches with spaCy's |
n_process |
the number of processes for spaCy's |
batch_size |
the number of documents that spaCy's |
... |
unused |
offsets |
logical; if |
When the option output = "data.frame" is selected, the
function returns a data.frame with the following fields, and with
start and end after them when offsets = TRUE.
textcontents of noun-phrase
root_textcontents of root token
start_idserial number ID of starting token: its position in
the document, starting at 1 and counting every token of spaCy's, as the
rows of spacy_parse(x) do. Whitespace tokens are counted, so where a
document has them this is not the position among the tokens of
spacy_tokenize(x) with default options, which leaves them out.
root_idserial number ID of root token
lengthnumber of words (tokens) included in a noun-phrase (e.g.
for a noun-phrase, "individual car owners", length = 3)
either a list or data.frame of tokens
The components of spaCy's pipeline that noun phrases do not need are left out
of the call, which makes it faster: with spaCy's English
models, the lemmatizer and the named entity recognizer. The output is the same as
when every component runs, so a component stays whenever a later one
that stays may read what it sets, and nothing is left out when the
pipeline has a component that is not one of spaCy's standard ones, or
finds its noun phrases by a function that is not spaCy's own for the
language, which may read any annotation. See
the details of spacy_parse(), and the article "Improving Performance"
on the package website.
## Not run: spacy_initialize() txt <- c(doc1 = "Natural language processing is a branch of computer science.", doc2 = "Paul earned a postgraduate degree from MIT.") spacy_extract_nounphrases(txt) spacy_extract_nounphrases(txt, output = "list") ## End(Not run)## Not run: spacy_initialize() txt <- c(doc1 = "Natural language processing is a branch of computer science.", doc2 = "Paul earned a postgraduate degree from MIT.") spacy_extract_nounphrases(txt) spacy_extract_nounphrases(txt, output = "list") ## End(Not run)
Removes the spaCy language model and any parsed documents from the Python
session, so that their memory can be released, and allows
spacy_initialize() to be called again, for instance with a different
language model or options.
spacy_finalize()spacy_finalize()
Python itself remains loaded in the R session: once started, it cannot be shut down or switched to a different Python installation or environment without restarting R.
Akitaka Matsuo
Initialize spaCy to call from R.
spacy_initialize( model = "en_core_web_sm", entity = TRUE, max_length = NULL, split_hyphens = TRUE, entity_patterns = NULL, overwrite_entities = TRUE, ... )spacy_initialize( model = "en_core_web_sm", entity = TRUE, max_length = NULL, split_hyphens = TRUE, entity_patterns = NULL, overwrite_entities = TRUE, ... )
model |
Language package for loading spaCy. Example: |
entity |
logical; if |
max_length |
integer; the maximum number of characters in a single
document that spaCy will accept ( |
split_hyphens |
logical; if |
entity_patterns |
rule-based entities to add to the pipeline: a
|
overwrite_entities |
logical; where an entity matched by
|
... |
not used. |
With entity_patterns, the entities found by the rules are returned by
spacy_parse() and spacy_extract_entity() like any others, also when
entity = FALSE. Patterns that ask for an entity type (ENT_TYPE) or for
tokens inside an entity (ENT_IOB) build on the entities of earlier
components, such as the model's ner or a ruler saved with the model, so
they give a warning when no earlier component sets entities, for instance
with entity = FALSE. Phrases are tokenized with the pipeline's own
tokenizer, and those marked case_insensitive match the lower case form of
each token. A component that changes the tokens, such as spaCy's
merge_entities, can stop phrases from matching when it comes before the
ruler, which gives a warning.
With split_hyphens = FALSE, the tokenizer still splits wherever the
model's tokenizer did other than at a single hyphen within a word: between
numbers, so that "3-4" is still three tokens ("3", "-" and "4"), where
quanteda's tokens(split_hyphens = FALSE) keeps it as one; at two or
more hyphens, as in "a–b"; and at the start or end of a word. The models
were trained on text with hyphenated words split, so their tags, lemmas and
dependencies for a hyphenated word kept whole can differ from those for its
parts. Only the language's default infix rules are changed: a model saved
with infix rules of its own, or whose tokenizer is not spaCy's rule-based
one, as for Chinese and Japanese, is left as it is. A warning is given if
the tokenizer still splits some hyphenated words, between letters or
between a letter and a digit, for whatever reason. Many languages, such as German, do not split
them in the first place. Phrase patterns of a ruler saved with the model,
such as an entity_ruler, were tokenized when the model was saved, so
those containing hyphenated words may no longer match; changing the
tokenizer gives a warning when an active component has phrase patterns.
Those of entity_patterns are tokenized after the change.
Phrases are matched quickly, even many thousands of them, and so are
patterns of a single token with a regular expression, such as dictionary
values with a wildcard, which spacyr combines into one regular expression
for each label. Other token patterns are checked one by one, and so are
phrases marked case_insensitive when the patterns also include phrases
that are not, which makes parsing slower when there are many of them.
Unless the environment variable TOKENIZERS_PARALLELISM is already set,
spacy_initialize() sets it to "false". Pipelines that use Hugging
Face's tokenizers library, such as some built with
spacy-transformers, otherwise print a warning about disabling
parallelism, with versions of tokenizers before 0.22.2, again and again
until R is restarted, once the R process is forked after the library has
been used, for instance by parallel::mcparallel(); saving a file in
RStudio has also been reported to trigger it. The setting controls the
library's tokenizer threads; its effect on total runtime depends on the
pipeline and the workload. It applies to the whole R process, Python
included, and stays after spacy_finalize(); if initialization fails, the
previous value is restored. A value set before calling
spacy_initialize() is kept, even an empty one, which tokenizers reads
as "false". Setting Sys.setenv(TOKENIZERS_PARALLELISM = "true") turns
off the library's safeguard against deadlocks: a forked process, such as a
worker of parallel::mclapply(), or of n_process greater than 1 when the
workers are started by fork, that uses tokenizers after the parent has
used it can then hang. Leave the setting at "false" whenever that can
happen.
PyTorch's warning that torch.jit.script is deprecated is not shown while
the model is loaded. A library that transformer pipelines such as
en_core_web_trf require calls that function, so the warning would come
with every such pipeline, whatever the user does. On Python 3.14 or later,
PyTorch warns instead that torch.jit.script is not supported and may
break, and that warning is shown: an environment with an earlier version
of Python avoids it.
R for macOS has its own copy of the OpenMP runtime, libomp.dylib, which
packages such as data.table load, and PyTorch, which transformer
pipelines such as en_core_web_trf install, bundles another. A process
that loads both is ended by the second, with the message
"OMP: Error #15", and spaCy imports PyTorch whenever it is installed, so
that the R session would end in spacy_initialize() for any language
model.
To prevent this, spacy_initialize() can replace PyTorch's copy in the
Python environment, torch/lib/libomp.dylib, by a link to the runtime that
R has loaded, so that the process has only one. It says so in a message,
and keeps the original beside the link as libomp.dylib.orig. This happens
once for an environment, and again after PyTorch is reinstalled or updated
in it. PyTorch then uses R's runtime also when the environment is used
outside R.
Because this changes files of the Python environment, the option
spacyr.openmp.fix says where it may be done:
"auto"(the default) only in the virtual environment that
spacyr manages, which spacy_install() creates: the one named by
SPACY_PYTHON, by default "r-spacyr". A Python chosen with
RETICULATE_PYTHON is not changed.
"always"in any Python environment, including one chosen with
RETICULATE_PYTHON, which may be shared with other projects or managed
by conda or another tool.
"never"in none.
Where the conflict is found and the change is not allowed,
spacy_initialize() stops with an error before spaCy is loaded, and
changes no file. The error gives the command for making the change
yourself; set options(spacyr.openmp.fix = "always") to let
spacyr make it.
After making the link, spacy_initialize() tests PyTorch with R's runtime
in a separate Python process, by importing it and computing with two
threads, with a 180-second time limit. If the test fails, cannot be
started, or does not finish, PyTorch's own runtime is put back and
spacy_initialize() stops with an error, whatever the reason for the
failure: an error is preferable to the end of the R session. Should the
runtime not be put back, the error says so and how to do it.
A passed test is recorded in the file libomp.dylib.spacyr-verified beside
the runtime, with what was tested: the link, R's runtime, PyTorch's own
runtime and PyTorch's libraries. While all of these are as recorded, later
sessions use the link without testing it again. When any of them has
changed, as after an update of R or of PyTorch, or when there is no record,
as after a test that was interrupted, the link is tested again before it is
used. In an environment that spacy_initialize() may not change, a link
without a record is tested in every session, and no record is written.
R sessions that use the same environment coordinate through a lock on the directory of the runtime, which the operating system releases when a session ends. A session that changes or tests the runtime holds the lock exclusively. Every other session shares it from before it looks at the runtime until spaCy is loaded, so that the runtime cannot be changed between its being checked and its being loaded; sessions that share the lock do not wait for each other. The directory is locked, and not a file in it, so that users of an environment that they cannot write to, such as one installed for all users of a computer, take part as well. A session waits up to 300 seconds for other sessions, then stops with an error. The lock coordinates spacyr sessions only: stop them before updating PyTorch with another tool.
The replacement and its backup are staged in the same directory and
renamed into place, with each operation checked, and a failed replacement
leaves the previous runtime and backup in place. A link that has no
libomp.dylib.orig beside it, such as one made by hand, is pointed at R's
runtime as well; the link it was is kept as libomp.dylib.spacyr-previous
until PyTorch has passed its test, and put back if it fails. A dangling
link that cannot be repaired stops initialization. To undo a completed
repair, first stop sessions using the environment, then rename
libomp.dylib.orig to libomp.dylib, replacing the link, and delete
libomp.dylib.spacyr-verified.
Akitaka Matsuo, Johannes B. Gruber
## Not run: # academic titles as part of a person's name titles <- c("dr", "dr.", "prof", "prof.", "professor") pats <- as_entity_patterns(list( label = "PERSON", pattern = list(list(LOWER = list(IN = titles)), list(ENT_TYPE = "PERSON", ENT_IOB = "B"), list(ENT_TYPE = "PERSON", ENT_IOB = "I", OP = "*")))) spacy_initialize(entity_patterns = pats) spacy_extract_entity("Prof. Jane Smith met Dr Bob Jones in Paris.") spacy_finalize() # phrases, with labels as names spacy_initialize(entity_patterns = c(ORG = "Acme Widgets", GPE = "Ruritania")) spacy_finalize() ## End(Not run)## Not run: # academic titles as part of a person's name titles <- c("dr", "dr.", "prof", "prof.", "professor") pats <- as_entity_patterns(list( label = "PERSON", pattern = list(list(LOWER = list(IN = titles)), list(ENT_TYPE = "PERSON", ENT_IOB = "B"), list(ENT_TYPE = "PERSON", ENT_IOB = "I", OP = "*")))) spacy_initialize(entity_patterns = pats) spacy_extract_entity("Prof. Jane Smith met Dr Bob Jones in Paris.") spacy_finalize() # phrases, with labels as names spacy_initialize(entity_patterns = c(ORG = "Acme Widgets", GPE = "Ruritania")) spacy_finalize() ## End(Not run)
Install spaCy in a self-contained environment, including specified language models.
spacy_install( version = "latest", lang_models = "en_core_web_sm", ask = interactive(), force = FALSE, ... )spacy_install( version = "latest", lang_models = "en_core_web_sm", ask = interactive(), force = FALSE, ... )
version |
character; spaCy version to install (see details). |
lang_models |
character; language models to be installed. Defaults
|
ask |
logical; ask whether to proceed during the installation. By default, questions are only asked in interactive sessions. |
force |
ignore if spaCy/the lang_models is already present and install it anyway. |
... |
not used. |
The function checks whether a suitable installation of Python is
present on the system and installs one via
reticulate::install_python() otherwise. "Suitable" means a version of
Python supported by the spaCy release being installed, as declared on
PyPI (if PyPI cannot be reached, any Python found is used). It then
creates a virtual environment with the necessary packages in the default
location chosen by reticulate::virtualenv_root().
For a spaCy version range, pip selects a release compatible with the
environment's Python.
An existing environment keeps the Python version it was created with. If
that version is not supported by the spaCy release being installed,
spacy_install() stops with an error; run spacy_uninstall() and then
spacy_install() to recreate the environment with a suitable Python.
If you want to install a different version of Python than the default, you
should call reticulate::install_python() directly. If you want
to create or use a different virtual environment, you can use, e.g.,
Sys.setenv(SPACY_PYTHON = "path/to/directory").
## Not run: # install the latest version of spaCy spacy_install() # update spaCy spacy_install(force = TRUE) # install an older version spacy_install(version = "3.1.0") # install with GPU enabled spacy_install(version = "cuda-autodetect") # install on Apple ARM processors spacy_install(version = "apple") # install an old custom version spacy_install(version = "[cuda-autodetect]==3.2.0") # install several models with spaCy spacy_install(lang_models = c("en_core_web_sm", "de_core_news_sm")) # install spaCy to an existing virtual environment Sys.setenv(RETICULATE_PYTHON = "path/to/python") spacy_install() ## End(Not run)## Not run: # install the latest version of spaCy spacy_install() # update spaCy spacy_install(force = TRUE) # install an older version spacy_install(version = "3.1.0") # install with GPU enabled spacy_install(version = "cuda-autodetect") # install on Apple ARM processors spacy_install(version = "apple") # install an old custom version spacy_install(version = "[cuda-autodetect]==3.2.0") # install several models with spaCy spacy_install(lang_models = c("en_core_web_sm", "de_core_news_sm")) # install spaCy to an existing virtual environment Sys.setenv(RETICULATE_PYTHON = "path/to/python") spacy_install() ## End(Not run)
Deprecated. spacy_install now installs to a virtual environment by default.
spacy_install_virtualenv(...)spacy_install_virtualenv(...)
... |
not used |
Checks, without starting Python, whether spaCy (and optionally one or more
language models) is installed in the environment that spacy_initialize()
will use: the one set by RETICULATE_PYTHON if set, or otherwise the
virtual environment named by SPACY_PYTHON (by default "r-spacyr"). This
is useful, for instance, to skip examples or tests when spaCy is not
available. If a different interpreter is already running in the R session
and prevents use of the named virtual environment, returns FALSE.
spacy_is_installed(lang_models = NULL)spacy_is_installed(lang_models = NULL)
lang_models |
character; names of language models that must also be
installed, e.g. |
TRUE if spaCy and all lang_models are installed, FALSE
otherwise.
spacy_install(), spacy_download_langmodel()
spacy_is_installed() spacy_is_installed("en_core_web_sm")spacy_is_installed() spacy_is_installed("en_core_web_sm")
Find the tokens that match patterns, using spaCy's rule-based matchers
(see https://spacy.io/usage/rule-based-matching). A pattern describes
either a sequence of adjacent tokens, or tokens that are connected in the
dependency parse, wherever they are in the sentence: the verb of a passive
clause together with its subject and its agent, for instance. A token is
described by its attributes, which can be those that the language model
assigns, such as the part of speech or the dependency relation. Words and
phrases can be matched too, given as in quanteda: as a character
vector, a quanteda::phrase() object or a dictionary, with wildcards or
regular expressions according to valuetype. Every kind of pattern gives
rows of the same table. Unlike the patterns given to
spacy_initialize() as entity_patterns, these do not change the
pipeline or the entities of a document.
spacy_match( x, pattern, valuetype = c("glob", "regex", "fixed"), case_insensitive = TRUE, overlap = c("longest", "all", "first"), n_process = 1L, batch_size = NULL, ..., offsets = FALSE )spacy_match( x, pattern, valuetype = c("glob", "regex", "fixed"), case_insensitive = TRUE, overlap = c("longest", "all", "first"), n_process = 1L, batch_size = NULL, ..., offsets = FALSE )
x |
a character object, a quanteda corpus, or a TIF-compliant corpus data.frame (see https://github.com/ropenscilabs/tif) |
pattern |
the patterns to match. The first four kinds are lexical
patterns, which describe tokens by their text and to which
The others are in spaCy's own structure, and set how they match themselves:
|
valuetype |
how the strings of lexical patterns are read: |
case_insensitive |
logical; if
|
overlap |
which matches of sequences to return where matches of the
same label overlap: |
n_process |
the number of processes for spaCy's |
batch_size |
the number of documents that spaCy's |
... |
not used. An argument that is not one of those of this function is an error. |
offsets |
logical; if |
Patterns are matched against spaCy's tokens, and an attribute can only
match when a component of the pipeline sets it: DEP needs the parser,
for instance, and spaCy gives an error when the component is missing.
Patterns that ask for an entity type (ENT_TYPE or ENT_IOB) give a
warning when no component sets entities, as after
spacy_initialize(entity = FALSE), since they then match nothing. The
labels of tags and dependency relations differ between language models;
spacy_parse(x, tag = TRUE, dependency = TRUE) shows those of the
model in use. A match is only as good as the model's annotation of the
text.
The values of spaCy's set operators (IN, NOT_IN, IS_SUBSET,
IS_SUPERSET and INTERSECTS) can be vectors of any length, and whole
numbers need not be integers, as for as_entity_patterns().
Lexical patterns are compared with spaCy's tokens, which differ from
those of quanteda::tokens(): spaCy's English models split "U.K.-based"
into three tokens, for instance. A string of a lexical pattern is one
token, and matches only where spaCy made the same token:
phrase("Acme, Inc.") asks for a token Acme,, which spaCy does not
make, while phrase("Acme , Inc.") matches the three tokens of
"Acme, Inc.".
spacy_tokenize() shows the tokens of a text. spaCy also makes a token of
a space that follows another space, which a pattern of a space matches.
To match as quanteda does on the same tokens, with its regular
expressions, apply quanteda::index() or quanteda::tokens_lookup() to
quanteda::as.tokens(spacy_parse(x)).
A string without a wildcard is compared with the token's text or, with
case_insensitive = TRUE, its lower case form (spaCy's ORTH and
LOWER). A glob with a wildcard becomes a regular expression for the
whole of that text or lower case form, in which a wildcard stands for any
characters, including the newlines of spaCy's whitespace tokens. Lower
case is spaCy's throughout, so that a pattern ignores case in the same
way with a wildcard as without. A regular expression is applied to
the token's text, with the flag (?i) when case_insensitive = TRUE.
The phrases of a spacyr_entity_patterns object, and dictionary values
without a wildcard, are split into tokens by spaCy's tokenizer, and match
the same sequence of tokens in a document, as described for
as_entity_patterns(). They are matched with spaCy's PhraseMatcher,
which stays fast for many thousands of phrases, as are the sequences of
lexical patterns that have no wildcard or regular expression. A phrase
that matches in
any case, as dictionary values do, is tokenized as it is written, and
spaCy's tokenizer can split the same word differently in another case:
it keeps "Inc." as one token but splits "inc." into two, so the phrase
"acme widgets, inc." does not match the text "Acme Widgets, Inc.",
while the phrase "Acme Widgets, Inc." in any case does. A warning is
given when
a component of the pipeline, such as merge_entities, changes the tokens
of the documents, since these phrases may then not match.
The operators in the REL_OP of a dependency pattern are spaCy's: among
others, "A > B" when B is a direct dependent of A, "A < B" when B is
the head of A, "A >> B" when B is anywhere below A, and "A . B" when B
directly follows A; see
https://spacy.io/usage/rule-based-matching#dependencymatcher for all of
them. A dependency pattern can match many times in a sentence: a verb and
any one of its dependents gives one match for each dependent. The pipeline
needs a dependency parser, or another component that sets dependencies:
when pattern holds a dependency pattern that relates nodes, a document
that has no dependency parse is an error, rather than a document without
matches.
Matching adds little to the time that parsing takes, except for many
token patterns: a few thousand make it much slower, so give phrases as
lexical patterns or phrases where you can, not as token patterns. Lexical
patterns and dictionary values with wildcards or regular expressions are
token patterns, but those of a single token are combined into one for
each label. Patterns that need no entities are faster after
spacy_initialize(entity = FALSE).
A data.frame with the same columns for every kind of pattern,
and no rows when nothing matches. A match of a sequence is one row. A
match of a dependency pattern is one row for each node of the pattern,
each of length 1, with the same match_id; two nodes can match the
same token, which then has a row for each.
doc_idthe document
match_idthe number of the match within the document, starting
at 1 in each document, so that doc_id and match_id together
identify a match
labelthe label of the pattern that matched. It does not say which of a label's alternative patterns matched, which spaCy does not report.
nodefor a dependency pattern, the name of the node that the
token matched, from RIGHT_ID; NA for a sequence
sentence_id, token_id
the sentence of the first token of the
sequence, or of the node's token, and the position of that token in its
sentence, both starting at 1 as in spacy_parse(). A sequence that
crosses a sentence boundary is given the sentence of its first token.
Both are NA when the document has no sentence boundaries, as when the
pipeline has neither a parser nor a sentence segmenter.
textthe matched text: of the whole sequence, or of the node's token
start_idthe position in the document of the first token of
the sequence, or of the node's token, starting at 1 and counting every
token of spaCy's, as the rows of spacy_parse() do
lengththe number of tokens: of the sequence, or 1 for a node
start, end
only with offsets = TRUE: the positions in the
text of the first and the last character of the sequence, or of the
node's token
Rows are in the order of the documents in x. Within a document,
matches are in the order of the start_id of their first row: the
first token of a sequence, or the token of the first node of a
dependency pattern. Of the matches that start at the same token,
sequences come first, by length (the shortest first) and then by the
order of the labels in pattern; matches of dependency patterns follow,
by the positions of the tokens of their other nodes, taken in the order
of the nodes, and then by the order of the labels. match_id numbers
the matches of a document in that order, sequences and dependency
matches together, and the rows of a dependency match are in the order of
the pattern's nodes. The order does not depend on overlap.
What pattern can be, and which arguments apply to each kind:
pattern |
Meaning | Label | valuetype, case_insensitive |
overlap |
| character vector | each element describes one token | its name, or else its text | apply | applies |
phrase() object, or a list of character vectors |
each element is a sequence, with one string for each token; the strings are not tokenized again | its name, or else its strings joined by a space | apply, to each string | applies |
| quanteda dictionary | converted by as_entity_patterns(): a value without a wildcard is a phrase that spaCy tokenizes, and one with a wildcard or a regular expression is split at its spaces |
the top-level key | apply | applies |
| collocations | each is a sequence of its words, matched as they are | the collocation | only case_insensitive applies; a valuetype other than "fixed" is an error |
applies |
| named list of spaCy token patterns | a sequence of tokens described by their attributes | the name | an error if given | applies |
spacyr_entity_patterns object |
its phrases, tokenized by spaCy, and its token patterns | its label |
an error if given | applies |
| named list of dependency patterns | one token for each node, anywhere in a sentence | the name | an error if given | does not apply, and has no effect when there are no other patterns |
A list can hold character vectors, token patterns and dependency
patterns together; valuetype and case_insensitive then apply to its
character vectors.
How each kind is matched:
| Sequences of tokens | Dependency patterns | |
| Matched by spaCy's | PhraseMatcher, for lexical patterns and dictionary values without a wildcard or a regular expression, and for the phrases of entity patterns; otherwise Matcher |
DependencyMatcher |
| Patterns for one label | any number, as alternatives | one |
n_process, batch_size |
apply | apply |
| Rows for one match | one | one for each node |
| The pipeline needs | the components that set the attributes asked for: only its tokenizer for lexical patterns and phrases | a dependency parse, in every document |
Patterns of every kind are matched in one pass over the documents, so the texts are parsed once for a list that holds both token and dependency patterns.
overlap = "longest", the default, chooses among overlapping matches as
quanteda::tokens_lookup() does with its default, nested_scope = "key":
no token is in two matches of the same key, and a value that lies inside a
value of another key is a match for both keys. The two are equivalent
when they start from the same candidate spans under the same keys, and
then give the same number of matches for each key in each document.
Applying tokens_lookup() to spaCy's tokens,
quanteda::as.tokens(spacy_parse(x)), does not guarantee that. In
particular:
A dictionary value without a wildcard is a phrase, which spaCy's
tokenizer splits into tokens, while quanteda splits every value
at its spaces. The value "Acme, Inc." matches the three tokens Acme,
, and Inc. here, where tokens_lookup() looks for a token Acme,
and finds nothing.
The values of a dictionary's nested keys are labelled here by their
top-level key, which corresponds to tokens_lookup(levels = 1). Its
default, levels = 1:5, reports nested keys such as place.us
separately, and so also keeps matches of two of them that overlap.
A match is a distinct pair of doc_id and match_id, not a row: count
those to count matches, since a match of a dependency pattern has a row
for each node. With one row for each match,
m1 <- m[!duplicated(m[c("doc_id", "match_id")]), ], the labels of each
document are tokens as tokens_lookup() returns them:
quanteda::as.tokens(split(m1$label, factor(m1$doc_id, levels = ids))).
The levels ids are the identifiers of all the documents, which keep
those that have no match: names(x) for a named character vector,
sprintf("text%d", seq_along(x)) for an unnamed one,
as.character(x$doc_id) for a data.frame with the columns doc_id and
text, and quanteda::docnames(x) for a corpus. The "Rule-Based
Matching" article shows the counts made from them.
quanteda::kwic() follows a different rule, which no value of overlap
gives: it drops a match only when every one of its tokens is in another
match, of any pattern. So it drops "New York" inside another label's "New
York Times", which overlap = "longest" keeps, and keeps both of two
matches of one label that partly overlap, of which overlap = "longest"
keeps one. A concordance of the matches themselves, with
kwic(index = as_index(m)), shows the matches that overlap kept: see
as_index().
The components of spaCy's pipeline that the patterns do not ask for are
left out of the call, which makes it faster. Phrases, words and the
values of a dictionary are matched on the text of the tokens, and need
only the parser, which sets the sentences. A pattern on POS, TAG or
MORPH also needs the components that set the tags, one on LEMMA the
lemmatizer, one on DEP or a dependency pattern the dependencies, and
one on ENT_TYPE the entities. The output is the same as when every
component runs, by the rules in the details of spacy_parse(). Nothing
is left out when a pattern asks for an attribute that is not one of
spaCy's token attributes known here, such as an extension attribute
(_).
as_entity_patterns() and spacy_initialize() to make matches
named entities, and as_index() to show matches in their context with
quanteda::kwic().
## Not run: spacy_initialize() txt <- c(doc1 = "The book was written by Jane. Jane wrote the book.", doc2 = "Mistakes were made, and the report is being rewritten.") # words, with wildcards as in quanteda, in any case spacy_match(txt, "writ*") # labelled by their names spacy_match(txt, c(WRITE = "*writ*", WRITE = "wrote", ERROR = "mistake*")) # a sequence of tokens needs phrase(): a character element is one token, # also when it contains a space, so the first of these matches nothing spacy_match(txt, "the book*") spacy_match(txt, quanteda::phrase("the book*")) # the same, as a list of character vectors, with a label spacy_match(txt, list(TITLE = c("the", "book*"))) # regular expressions, which are Python's spacy_match(txt, "^(re)?writ", valuetype = "regex") # matching case spacy_match(txt, c("the", "jane"), case_insensitive = FALSE) spacy_match(txt, quanteda::phrase("The book"), valuetype = "fixed", case_insensitive = FALSE) # passive verbs, by the dependency and tag labels of the English models: # a passive auxiliary, any adverbs or further auxiliaries, and a past # participle passive <- list(list(DEP = "auxpass"), list(DEP = list(IN = c("advmod", "neg", "aux", "auxpass")), OP = "*"), list(TAG = "VBN")) spacy_match(txt, list(PASSIVE = passive)) # adjectives before a noun: the longest match where matches of a label # overlap, which is the default, or every match adj_noun <- list(ADJ_NOUN = list(list(POS = "ADJ", OP = "+"), list(POS = "NOUN"))) spacy_match("A big red shiny ball.", adj_noun) spacy_match("A big red shiny ball.", adj_noun, overlap = "all") # two labels, the second with alternative patterns spacy_match(txt, list( DET_NOUN = list(list(POS = "DET"), list(POS = "NOUN")), WRITE = list(list(list(LEMMA = "write")), list(list(LEMMA = "rewrite"))) )) # phrases that spaCy tokenizes, matched exactly or in any case spacy_match(txt, as_entity_patterns(c(TITLE = "the book"))) spacy_match(txt, as_entity_patterns(c(TITLE = "the book"), case_insensitive = TRUE)) # a quanteda dictionary, with its wildcards dict <- quanteda::dictionary(list(writing = c("writ*", "wrote", "the book"), error = "mistake*")) spacy_match(txt, dict) spacy_match(txt, dict, case_insensitive = FALSE) # a dependency pattern for passive clauses: a past participle with a # passive subject and a passive auxiliary as its dependents clause <- list( list(RIGHT_ID = "verb", RIGHT_ATTRS = list(TAG = "VBN")), list(LEFT_ID = "verb", REL_OP = ">", RIGHT_ID = "subject", RIGHT_ATTRS = list(DEP = "nsubjpass")), list(LEFT_ID = "verb", REL_OP = ">", RIGHT_ID = "aux", RIGHT_ATTRS = list(DEP = "auxpass")) ) m <- spacy_match(txt, list(CLAUSE = clause)) m # one row for each match, with a column for each node reshape(m[, c("doc_id", "match_id", "node", "text")], idvar = c("doc_id", "match_id"), timevar = "node", direction = "wide") # token and dependency patterns in one list spacy_match(txt, list(PASSIVE = passive, CLAUSE = clause)) ## End(Not run)## Not run: spacy_initialize() txt <- c(doc1 = "The book was written by Jane. Jane wrote the book.", doc2 = "Mistakes were made, and the report is being rewritten.") # words, with wildcards as in quanteda, in any case spacy_match(txt, "writ*") # labelled by their names spacy_match(txt, c(WRITE = "*writ*", WRITE = "wrote", ERROR = "mistake*")) # a sequence of tokens needs phrase(): a character element is one token, # also when it contains a space, so the first of these matches nothing spacy_match(txt, "the book*") spacy_match(txt, quanteda::phrase("the book*")) # the same, as a list of character vectors, with a label spacy_match(txt, list(TITLE = c("the", "book*"))) # regular expressions, which are Python's spacy_match(txt, "^(re)?writ", valuetype = "regex") # matching case spacy_match(txt, c("the", "jane"), case_insensitive = FALSE) spacy_match(txt, quanteda::phrase("The book"), valuetype = "fixed", case_insensitive = FALSE) # passive verbs, by the dependency and tag labels of the English models: # a passive auxiliary, any adverbs or further auxiliaries, and a past # participle passive <- list(list(DEP = "auxpass"), list(DEP = list(IN = c("advmod", "neg", "aux", "auxpass")), OP = "*"), list(TAG = "VBN")) spacy_match(txt, list(PASSIVE = passive)) # adjectives before a noun: the longest match where matches of a label # overlap, which is the default, or every match adj_noun <- list(ADJ_NOUN = list(list(POS = "ADJ", OP = "+"), list(POS = "NOUN"))) spacy_match("A big red shiny ball.", adj_noun) spacy_match("A big red shiny ball.", adj_noun, overlap = "all") # two labels, the second with alternative patterns spacy_match(txt, list( DET_NOUN = list(list(POS = "DET"), list(POS = "NOUN")), WRITE = list(list(list(LEMMA = "write")), list(list(LEMMA = "rewrite"))) )) # phrases that spaCy tokenizes, matched exactly or in any case spacy_match(txt, as_entity_patterns(c(TITLE = "the book"))) spacy_match(txt, as_entity_patterns(c(TITLE = "the book"), case_insensitive = TRUE)) # a quanteda dictionary, with its wildcards dict <- quanteda::dictionary(list(writing = c("writ*", "wrote", "the book"), error = "mistake*")) spacy_match(txt, dict) spacy_match(txt, dict, case_insensitive = FALSE) # a dependency pattern for passive clauses: a past participle with a # passive subject and a passive auxiliary as its dependents clause <- list( list(RIGHT_ID = "verb", RIGHT_ATTRS = list(TAG = "VBN")), list(LEFT_ID = "verb", REL_OP = ">", RIGHT_ID = "subject", RIGHT_ATTRS = list(DEP = "nsubjpass")), list(LEFT_ID = "verb", REL_OP = ">", RIGHT_ID = "aux", RIGHT_ATTRS = list(DEP = "auxpass")) ) m <- spacy_match(txt, list(CLAUSE = clause)) m # one row for each match, with a column for each node reshape(m[, c("doc_id", "match_id", "node", "text")], idvar = c("doc_id", "match_id"), timevar = "node", direction = "wide") # token and dependency patterns in one list spacy_match(txt, list(PASSIVE = passive, CLAUSE = clause)) ## End(Not run)
The spacy_parse() function calls spaCy to both tokenize and tag the
texts, and returns a data.frame of the results, with one row per token. The
function provides options for universal (pos) and detailed (tag)
part-of-speech tags, lemmatization (lemma), named entity recognition
(entity), dependency parsing (dependency), noun phrases (nounphrase),
the position of each token in its text (offsets), and any other token
attributes from spaCy (additional_attributes).
spacy_parse( x, pos = TRUE, tag = FALSE, lemma = TRUE, entity = TRUE, dependency = FALSE, nounphrase = FALSE, multithread, additional_attributes = NULL, n_process = 1L, batch_size = NULL, offsets = FALSE, ... )spacy_parse( x, pos = TRUE, tag = FALSE, lemma = TRUE, entity = TRUE, dependency = FALSE, nounphrase = FALSE, multithread, additional_attributes = NULL, n_process = 1L, batch_size = NULL, offsets = FALSE, ... )
x |
a character object, a quanteda corpus, or a TIF-compliant corpus data.frame (see https://github.com/ropenscilabs/tif) |
pos |
logical whether to return universal dependency POS tagset (https://universaldependencies.org/u/pos/) |
tag |
logical whether to return detailed part-of-speech tags; the English language models use the OntoNotes 5 version of the Penn Treebank tag set (https://spacy.io/models/en). The tag sets of other language models are listed under "Label scheme" on https://spacy.io/models. |
lemma |
logical; include lemmatized tokens in the output (the quality of lemmatization depends on the language model) |
entity |
logical; if |
dependency |
logical; if |
nounphrase |
logical; if |
multithread |
deprecated; it no longer has any effect, and gives a
warning if supplied. Documents are always processed in
batches with spaCy's |
additional_attributes |
a character vector; this option is for
extracting additional attributes of tokens from spaCy. When the names of
attributes are supplied, the output data.frame will contain additional
variables corresponding to the names of the attributes. For instance, when
|
n_process |
the number of processes for spaCy's |
batch_size |
the number of documents that spaCy's |
offsets |
logical; if |
... |
not used directly |
The components of spaCy's pipeline whose results the options do not ask
for are left out of the call, which makes it faster: the named entity
recognizer with entity = FALSE; the lemmatizer with lemma = FALSE; and
the tagger and the attribute ruler when pos, tag, lemma and
nounphrase are all FALSE. The output is the same as when every
component runs, so a component stays whenever it sets something that the
output has, or that a later component may read:
The parser always runs, since it sets the sentences.
An attribute ruler stays if any of its rules sets something that is
returned. That of spaCy's English models also sets the dependency of
whitespace tokens, so with dependency = TRUE it stays, and so does
the tagger, whose tags its rules read.
With entity rules from spacy_initialize(entity_patterns = ) and
entity = TRUE, the components that the rules may read stay.
A component stays if the model of a later component reads what it sets, as an entity recognizer that was trained to use the part of speech does. The models of spaCy's own pipelines read only the text of the tokens. What a model reads is told from its settings; a model that is not built by spaCy's own functions is taken to read everything.
Nothing is left out when additional_attributes are asked for, or when
the pipeline has a component that is not one of spaCy's standard ones.
Nothing is left out either when the pipeline's tokenizer is not spaCy's own. Such a tokenizer can give the documents a function of its own to find the sentences, which may read any annotation.
With nounphrase = TRUE, nothing is left out either when the pipeline
finds its noun phrases by a function that is not spaCy's own for the
language, which may read any annotation.
See the article "Improving Performance" on the package website.
a data.frame of tokenized, parsed, and annotated tokens, of class
spacyr_parsed. It keeps the names of all the documents of x, also of
those in which spaCy found no tokens, and the document variables of a
quanteda corpus, for the quanteda methods such
as quanteda::as.tokens().
## Not run: spacy_initialize() # See Chap 5.1 of the NLTK book, http://www.nltk.org/book/ch05.html txt <- "And now for something completely different." spacy_parse(txt) spacy_parse(txt, pos = TRUE, tag = TRUE) spacy_parse(txt, dependency = TRUE) txt2 <- c(doc1 = "The fast cat catches mice.\\nThe quick brown dog jumped.", doc2 = "This is the second document.", doc3 = "This is a \\\"quoted\\\" text." ) spacy_parse(txt2, entity = TRUE, dependency = TRUE) txt3 <- "We analyzed the Supreme Court with three natural language processing tools." spacy_parse(txt3, entity = TRUE, nounphrase = TRUE) spacy_parse(txt3, additional_attributes = c("like_num", "is_punct")) # the position of each token in the text parsed <- spacy_parse(txt3, offsets = TRUE) substring(txt3, parsed$start, parsed$end) ## End(Not run)## Not run: spacy_initialize() # See Chap 5.1 of the NLTK book, http://www.nltk.org/book/ch05.html txt <- "And now for something completely different." spacy_parse(txt) spacy_parse(txt, pos = TRUE, tag = TRUE) spacy_parse(txt, dependency = TRUE) txt2 <- c(doc1 = "The fast cat catches mice.\\nThe quick brown dog jumped.", doc2 = "This is the second document.", doc3 = "This is a \\\"quoted\\\" text." ) spacy_parse(txt2, entity = TRUE, dependency = TRUE) txt3 <- "We analyzed the Supreme Court with three natural language processing tools." spacy_parse(txt3, entity = TRUE, nounphrase = TRUE) spacy_parse(txt3, additional_attributes = c("like_num", "is_punct")) # the position of each token in the text parsed <- spacy_parse(txt3, offsets = TRUE) substring(txt3, parsed$start, parsed$end) ## End(Not run)
Efficient tokenization (without POS tagging, dependency parsing, lemmatization, or named entity recognition) of texts using spaCy.
spacy_tokenize( x, what = c("word", "sentence"), remove_punct = FALSE, remove_url = FALSE, remove_numbers = FALSE, remove_separators = TRUE, remove_symbols = FALSE, padding = FALSE, multithread, output = c("list", "data.frame"), n_process = 1L, batch_size = NULL, ... )spacy_tokenize( x, what = c("word", "sentence"), remove_punct = FALSE, remove_url = FALSE, remove_numbers = FALSE, remove_separators = TRUE, remove_symbols = FALSE, padding = FALSE, multithread, output = c("list", "data.frame"), n_process = 1L, batch_size = NULL, ... )
x |
a character object, a quanteda corpus, or a TIF-compliant corpus data.frame (see https://github.com/ropenscilabs/tif) |
what |
the unit for splitting the text, available alternatives are:
|
remove_punct |
remove punctuation tokens. |
remove_url |
remove tokens that look like a url or email address. |
remove_numbers |
remove tokens that look like a number (e.g. "334", "3.1415", "fifty"). |
remove_separators |
remove spaces as separators when
all other remove functionalities (e.g. |
remove_symbols |
remove symbols. The symbols are either |
padding |
if |
multithread |
deprecated; it no longer has any effect, and gives a
warning if supplied. Documents are always processed in
batches with spaCy's |
output |
type of returning object. Either |
n_process |
the number of processes for spaCy's |
batch_size |
the number of documents that spaCy's |
... |
not used directly |
Splitting texts into words runs no component of spaCy's pipeline. Two
options need some of them, and leave out the others: what = "sentence"
needs the components that set the sentences, which is the parser in
spaCy's models, and remove_symbols = TRUE those that set the part of
speech, which in spaCy's English models are the tagger, the parser and
the attribute ruler. The output is the same as when every component
runs, by the rules described in the details of spacy_parse(): a
component stays whenever a later one that stays may read what it sets,
and nothing is left out when the pipeline has a component that is not
one of spaCy's standard ones, or a tokenizer that is not spaCy's own,
which can give the documents a function of its own to find the
sentences.
either list or data.frame of tokens
## Not run: spacy_initialize() txt <- "And now for something completely different." spacy_tokenize(txt) txt2 <- c(doc1 = "The fast cat catches mice.\\nThe quick brown dog jumped.", doc2 = "This is the second document.", doc3 = "This is a \\\"quoted\\\" text." ) spacy_tokenize(txt2) ## End(Not run)## Not run: spacy_initialize() txt <- "And now for something completely different." spacy_tokenize(txt) txt2 <- c(doc1 = "The fast cat catches mice.\\nThe quick brown dog jumped.", doc2 = "This is the second document.", doc3 = "This is a \\\"quoted\\\" text." ) spacy_tokenize(txt2) ## End(Not run)
Removes the virtual environment created by spacy_install()
spacy_uninstall(confirm = interactive())spacy_uninstall(confirm = interactive())
confirm |
logical; confirm before uninstalling spaCy? |
Upgrade spaCy (to a specific version).
spacy_upgrade( version = "latest", lang_models = NULL, ask = interactive(), force = TRUE, ... )spacy_upgrade( version = "latest", lang_models = NULL, ask = interactive(), force = TRUE, ... )
version |
character; spaCy version to install (see details). |
lang_models |
character; language models to be installed. Defaults
|
ask |
logical; ask whether to proceed during the installation. By default, questions are only asked in interactive sessions. |
force |
ignore if spaCy/the lang_models is already present and install it anyway. |
... |
passed on to |
The function checks whether a suitable installation of Python is
present on the system and installs one via
reticulate::install_python() otherwise. "Suitable" means a version of
Python supported by the spaCy release being installed, as declared on
PyPI (if PyPI cannot be reached, any Python found is used). It then
creates a virtual environment with the necessary packages in the default
location chosen by reticulate::virtualenv_root().
For a spaCy version range, pip selects a release compatible with the
environment's Python.
An existing environment keeps the Python version it was created with. If
that version is not supported by the spaCy release being installed,
spacy_install() stops with an error; run spacy_uninstall() and then
spacy_install() to recreate the environment with a suitable Python.
If you want to install a different version of Python than the default, you
should call reticulate::install_python() directly. If you want
to create or use a different virtual environment, you can use, e.g.,
Sys.setenv(SPACY_PYTHON = "path/to/directory").
## Not run: # install the latest version of spaCy spacy_install() # update spaCy spacy_install(force = TRUE) # install an older version spacy_install(version = "3.1.0") # install with GPU enabled spacy_install(version = "cuda-autodetect") # install on Apple ARM processors spacy_install(version = "apple") # install an old custom version spacy_install(version = "[cuda-autodetect]==3.2.0") # install several models with spaCy spacy_install(lang_models = c("en_core_web_sm", "de_core_news_sm")) # install spaCy to an existing virtual environment Sys.setenv(RETICULATE_PYTHON = "path/to/python") spacy_install() ## End(Not run)## Not run: # install the latest version of spaCy spacy_install() # update spaCy spacy_install(force = TRUE) # install an older version spacy_install(version = "3.1.0") # install with GPU enabled spacy_install(version = "cuda-autodetect") # install on Apple ARM processors spacy_install(version = "apple") # install an old custom version spacy_install(version = "[cuda-autodetect]==3.2.0") # install several models with spaCy spacy_install(lang_models = c("en_core_web_sm", "de_core_news_sm")) # install spaCy to an existing virtual environment Sys.setenv(RETICULATE_PYTHON = "path/to/python") spacy_install() ## End(Not run)