Package 'spacyr'

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

Help Index


An R wrapper to the spaCy NLP system

Description

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.

Author(s)

Ken Benoit and Akitaka Matsuo

References

https://spacy.io, https://spacyr.quanteda.io.

See Also

Useful links:


Create patterns for rule-based named entities

Description

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.

Usage

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,
  ...
)

Arguments

x

the patterns to convert:

  • a character vector of phrases, each matched exactly as a sequence of spaCy's tokens. Labels come from the names of x, as in c(ORG = "Acme Widgets"), or from label. With valuetype = "glob" or "regex", they can have wildcards or be regular expressions, as the values of a dictionary can.

  • a list of patterns in spaCy's own structure, each a list with the elements label, pattern and optionally id. pattern is either a single phrase or a list of token patterns, one per token, each a named list of token attributes such as list(LOWER = "dr"). See spaCy's rule-based matching for the attributes and operators available. A single pattern may also be given on its own, rather than in a list of patterns.

  • a data.frame with the columns label and pattern, and optionally id and case_insensitive. pattern is a character column of phrases, or a list column holding phrases or token patterns.

  • the entities found by spacy_extract_entity(), a data.frame with the columns text and ent_type, which become phrases and their labels. This turns the entities found in one set of texts into rules for others.

  • the entities found by entity_extract(), with the columns entity and entity_type, given with the concatenator that joined their tokens.

  • a quanteda dictionary, made by quanteda::dictionary(). Its top-level keys are the labels, with the values of any nested keys under them, unless levels says otherwise. A value without wildcards becomes a phrase. A value with wildcards (* for any characters, ⁠?⁠ for one) becomes a token pattern with one token for each part separated by spaces, as quanteda matches dictionary values to tokens, so that "dr * who" matches three tokens.

  • NULL, as spacy_extract_entity() returns when it finds no entities, which gives an empty set of patterns.

  • a spacyr_entity_patterns object, which is checked again, since it may have been edited as a data.frame.

...

not used.

label

character; the entity label of each phrase, such as "PERSON" or "ORG", either one for all phrases or one per phrase. If NULL (the default), the names of x are used.

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 ent_id_.

case_insensitive

logical; if TRUE, phrases match regardless of case. The default, FALSE, matches them exactly, as spaCy does, except for a dictionary, where it is TRUE, as in quanteda. It also applies to the parts of phrases and dictionary values that have wildcards or are regular expressions. It does not apply to token patterns, which set case through the attribute they match, such as ORTH (exact) or LOWER (any case). For a list, it applies to the patterns that do not set case_insensitive themselves; for a data.frame, it applies when there is no case_insensitive column.

valuetype

how phrases and the values of a dictionary are read: "fixed" for exact phrases, "glob" for wildcards (* for any characters, ⁠?⁠ for one), or "regex" for regular expressions, as in quanteda::tokens_lookup(). The default is "fixed" for a character vector, as suits the names of entities, and "glob" for a dictionary, as in quanteda. A phrase or value with a wildcard, and any with "regex", becomes a token pattern with one token for each part separated by spaces; any other is a phrase, which spaCy tokenizes. With "regex", each part is a regular expression for one of spaCy's tokens, in the dialect of Python's re module, not of R: for instance, "^\\p{L}+$" works in quanteda but stops spacy_initialize() with the error "bad escape \p". Since quanteda::dictionary() lowercases values by default, which changes escapes such as "\\D" to "\\d", make a dictionary of regular expressions with tolower = FALSE.

concatenator

for the output of entity_extract(), the character(s) that joined the tokens of each entity, which are replaced by spaces. It must be given, since a token that itself contains the concatenator, such as an underscore, is changed too; the output of spacy_extract_entity() keeps the text of each entity as it was, and is the better input.

levels

for a dictionary, the levels of its keys that become labels, as in quanteda::tokens_lookup(). The default, 1, labels every value by its top-level key. With more than one level, a value is labelled by its keys at those levels, joined by ".": with levels = 1:2, the values under us in place have the label "place.us". Values with no key at any of the levels are left out.

valuetype and levels are an error for an input that has no use for them: levels for anything but a dictionary, and valuetype for a list, a data.frame or a spacyr_entity_patterns object, whose phrases are matched as they are.

Details

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.

Value

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.

See Also

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

Examples

# 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")))

Convert matches, entities or noun phrases to a quanteda index

Description

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.

Usage

as_index(x)

Arguments

x

the output of spacy_match(), spacy_extract_entity() or spacy_extract_nounphrases(): a data.frame with the columns doc_id, start_id and length. It can also be NULL, which spacy_extract_entity() and spacy_extract_nounphrases() return when they find nothing, and which gives an index with no rows.

Details

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.

Value

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.

See Also

spacy_match(), spacy_extract_entity(), spacy_extract_nounphrases(), quanteda::kwic()

Examples

# 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)

Convert entity patterns of phrases to a quanteda dictionary

Description

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.

Usage

## S3 method for class 'spacyr_entity_patterns'
as.dictionary(x, ...)

Arguments

x

a spacyr_entity_patterns object, as as_entity_patterns() or entity_patterns_read() returns, whose patterns are all phrases

...

not used; any argument given here is an error

Details

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.

Value

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.

See Also

as_entity_patterns(), quanteda::dictionary(), quanteda::tokens_lookup()

Examples

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 short paragraph of text for testing

Description

A sample of text from the Irish budget debate of 2010 (531 tokens long).

Usage

data_char_paragraph

Format

An object of class character of length 1.


Sample short documents for testing

Description

A character object consisting of 30 short documents in plain text format for testing. Each document is one or two brief sentences.

Usage

data_char_sentences

Format

An object of class character of length 30.


Extract or consolidate entities from parsed documents

Description

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.

Usage

entity_extract(x, type = c("named", "extended", "all"), concatenator = "_")

entity_consolidate(x, concatenator = "_")

Arguments

x

output from spacy_parse().

type

type of named entities, either named, extended, or all. Extended entities are those of types DATE, TIME, PERCENT, MONEY, QUANTITY, ORDINAL and CARDINAL, and named entities are those of all other types. The entity types are those of the language model; see its "Label scheme" on https://spacy.io/models.

concatenator

the character(s) used to join the elements of multi-word named entities

Value

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.

Examples

## 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 and write entity patterns

Description

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.

Usage

entity_patterns_read(file, label = NULL, case_insensitive = FALSE)

entity_patterns_write(x, file)

Arguments

file

the path of the file to read or write. Its extension sets the format, and must be .jsonl for writing:

  • .jsonl: spaCy's own format, one pattern per line, each a JSON object with the keys label, pattern and optionally id, as written by spaCy's EntityRuler.to_disk();

  • .json: a JSON array of the same patterns;

  • .txt (reading only): one phrase per line, all with the label given by label. Empty lines are skipped.

label

character; for a .txt file, the label of its phrases.

case_insensitive

logical; for phrases, whether they match regardless of case. See as_entity_patterns().

x

patterns to write: a spacyr_entity_patterns object, or anything that as_entity_patterns() accepts.

Details

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.

Value

entity_patterns_read() returns a spacyr_entity_patterns object. entity_patterns_write() returns file, invisibly.

See Also

as_entity_patterns()

Examples

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)
}

Visualize the named entities of parsed documents

Description

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).

Usage

entity_visualize(x, entities = NULL, colors = NULL, view = FALSE)

Arguments

x

the output of spacy_parse(), best with offsets = TRUE (see Details), or of entity_consolidate()

entities

the entity labels to highlight, as a character vector such as c("PERSON", "ORG"). The default, NULL, highlights the entities of every label, and character(0) highlights none. The labels are those of the language model (see its "Label scheme" on https://spacy.io/models) and of any entity rules, and are matched regardless of case.

colors

a named character vector of colours for labels, such as c(ORG = "#7aecec", PERSON = "lightblue"), whose names are labels and whose values are colours in any form that CSS has. displaCy has colours of its own for the labels of spaCy's models, and shows other labels in grey.

view

logical; if TRUE, also open the result in the browser, or in the viewer that the browser option is set to (see utils::browseURL()).

Details

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.

Value

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.

See Also

spacy_parse(); entity_extract() and spacy_extract_entity() for the entities as data.

Examples

## 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)

Extract or consolidate noun phrases from parsed documents

Description

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.

Usage

nounphrase_extract(x, concatenator = "_")

nounphrase_consolidate(x, concatenator = "_")

Arguments

x

output from spacy_parse()

concatenator

the character(s) used to join elements of multi-word noun phrases

Value

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.

Examples

## 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)

quanteda methods for parsed texts

Description

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.

Usage

## 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)

Arguments

x

the output of spacy_parse(), or of entity_consolidate() or nounphrase_consolidate()

concatenator

the character that joins a token and its part of speech, when include_pos is not "none"

include_pos

which part of speech to add to each token, after concatenator: "none", the default, for none; "pos" for the column pos; or "tag" for the column tag

use_lemma

if TRUE, the tokens are the lemmas and not the tokens as they are in the text

...

not used

Details

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().

Value

  • 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().

Which documents there are

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.

Earlier versions

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.

See Also

spacy_parse(), as_index(), quanteda::as.tokens(), quanteda::docnames(), quanteda::ntoken()

Examples

## 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

Description

Download spaCy language models

Usage

spacy_download_langmodel(lang_models = "en_core_web_sm", force = FALSE)

Arguments

lang_models

character; language models to be installed. Defaults en_core_web_sm (English model). A vector of multiple model names can be used (e.g. c("en_core_web_sm", "de_core_news_sm")). A list of available language models and their names is available from the spaCy language models page.

force

ignore if spaCy/the lang_models is already present and install it anyway.

Details

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.

Value

Invisibly returns the installation log.

Examples

## 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)

Install a language model in a conda or virtual environment

Description

Deprecated. spacyr now always uses a virtual environment, making this function redundant.

Usage

spacy_download_langmodel_virtualenv(...)

Arguments

...

not used


Extract named entities from texts using spaCy

Description

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).

Usage

spacy_extract_entity(
  x,
  output = c("data.frame", "list"),
  type = c("all", "named", "extended"),
  multithread,
  n_process = 1L,
  batch_size = NULL,
  ...,
  offsets = FALSE
)

Arguments

x

a character object or a TIF-compliant corpus data.frame (see https://github.com/ropenscilabs/tif)

output

type of returned object, either "list" or "data.frame".

type

type of named entities, either named, extended, or all. Extended entities are those of types DATE, TIME, PERCENT, MONEY, QUANTITY, ORDINAL and CARDINAL, and named entities are those of all other types. The entity types are those of the language model; see its "Label scheme" on https://spacy.io/models.

multithread

deprecated; it no longer has any effect, and gives a warning if supplied. Documents are always processed in batches with spaCy's nlp.pipe(); use n_process and batch_size instead.

n_process

the number of processes for spaCy's nlp.pipe() to use: 1 (the default) processes the documents in the current R session's Python process, a larger number starts that many Python processes, and -1 uses all CPUs. Starting the processes and loading the model in each takes time, so more than one process helps only for large numbers of documents. A custom pipeline component must be defined in an importable Python module to be used in other processes.

batch_size

the number of documents that spaCy's nlp.pipe() processes together; NULL (the default) uses the pipeline's default (nlp.batch_size). Larger batches can be faster, but use more memory.

...

unused

offsets

logical; if TRUE, also return the position of each entity in its text as it was given in x, in the columns start and end: the positions of the entity's first and last characters, counted from 1 as in spacy_parse(), so that substring(text, start, end) gives the entities of a text. This needs output = "data.frame". It comes after ..., so it has to be given by its full name.

Details

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.

text

contents of entity

ent_type

type of entity (e.g. ORG for organizations)

start_id

serial 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.

length

number of words (tokens) included in a named entity (e.g. for an entity, "New York Stock Exchange"", length = 4)

Value

either a list or data.frame of tokens

Components that are left out

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.

Examples

## 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)

Extract noun phrases from texts using spaCy

Description

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).

Usage

spacy_extract_nounphrases(
  x,
  output = c("data.frame", "list"),
  multithread,
  n_process = 1L,
  batch_size = NULL,
  ...,
  offsets = FALSE
)

Arguments

x

a character object or a TIF-compliant corpus data.frame (see https://github.com/ropenscilabs/tif)

output

type of returned object, either "data.frame" or "list"

multithread

deprecated; it no longer has any effect, and gives a warning if supplied. Documents are always processed in batches with spaCy's nlp.pipe(); use n_process and batch_size instead.

n_process

the number of processes for spaCy's nlp.pipe() to use: 1 (the default) processes the documents in the current R session's Python process, a larger number starts that many Python processes, and -1 uses all CPUs. Starting the processes and loading the model in each takes time, so more than one process helps only for large numbers of documents. A custom pipeline component must be defined in an importable Python module to be used in other processes.

batch_size

the number of documents that spaCy's nlp.pipe() processes together; NULL (the default) uses the pipeline's default (nlp.batch_size). Larger batches can be faster, but use more memory.

...

unused

offsets

logical; if TRUE, also return the position of each noun phrase in its text as it was given in x, in the columns start and end: the positions of the noun phrase's first and last characters, counted from 1 as in spacy_parse(), so that substring(text, start, end) gives the noun phrases of a text. This needs output = "data.frame". It comes after ..., so it has to be given by its full name.

Details

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.

text

contents of noun-phrase

root_text

contents of root token

start_id

serial 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_id

serial number ID of root token

length

number of words (tokens) included in a noun-phrase (e.g. for a noun-phrase, "individual car owners", length = 3)

Value

either a list or data.frame of tokens

Components that are left out

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.

Examples

## 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)

Finalize spaCy

Description

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.

Usage

spacy_finalize()

Details

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.

Author(s)

Akitaka Matsuo


Initialize spaCy

Description

Initialize spaCy to call from R.

Usage

spacy_initialize(
  model = "en_core_web_sm",
  entity = TRUE,
  max_length = NULL,
  split_hyphens = TRUE,
  entity_patterns = NULL,
  overwrite_entities = TRUE,
  ...
)

Arguments

model

Language package for loading spaCy. Example: en_core_web_sm (English) and de_core_news_sm (German). Default is en_core_web_sm. This can also be the path to a model directory.

entity

logical; if FALSE is selected, named entity recognition is turned off in spaCy. This will speed up the parsing as it will exclude ner from the pipeline. For details of spaCy pipeline, see https://spacy.io/usage/processing-pipelines.

max_length

integer; the maximum number of characters in a single document that spaCy will accept (nlp.max_length), a whole number no larger than .Machine$integer.max. If NULL (the default), spaCy's default of 1,000,000 is used. Larger values require roughly 1GB of temporary memory per 100,000 characters for the parser and entity recogniser.

split_hyphens

logical; if TRUE (the default), words joined by a hyphen are split as the language model's tokenizer splits them, which for English makes three tokens of "eye-opening": "eye", "-" and "opening". If FALSE, the tokenizer no longer splits at a single hyphen between letters, or between a letter and a digit, so that "eye-opening" stays one token, and the rest of the pipeline, such as the tagger and lemmatizer, processes it as one. Note that the default differs from that of quanteda's quanteda::tokens(), whose split_hyphens = FALSE keeps hyphenated words together by default. See Details.

entity_patterns

rule-based entities to add to the pipeline: a spacyr_entity_patterns object, or anything that as_entity_patterns() accepts, such as a named character vector of phrases. spacyr adds spaCy's entity ruler, as spacyr_entity_ruler, at the end of the pipeline, after every component that sets entities; an entity ruler saved with the model stays as it is. If the model already has a component of that name, for instance because it was saved from a pipeline with rules added by spacyr, the new ruler is named spacyr_entity_ruler_2 (or the next free number). If NULL (the default), the pipeline is not changed.

overwrite_entities

logical; where an entity matched by entity_patterns overlaps one found by an earlier component, such as the model's named entity recognizer, the rule's entity is kept if TRUE (the default), and the earlier one if FALSE, so that the rules only add entities where none were found.

...

not used.

Details

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.

OpenMP on macOS

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.

Author(s)

Akitaka Matsuo, Johannes B. Gruber

See Also

as_entity_patterns()

Examples

## 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 virtual environment

Description

Install spaCy in a self-contained environment, including specified language models.

Usage

spacy_install(
  version = "latest",
  lang_models = "en_core_web_sm",
  ask = interactive(),
  force = FALSE,
  ...
)

Arguments

version

character; spaCy version to install (see details).

lang_models

character; language models to be installed. Defaults en_core_web_sm (English model). A vector of multiple model names can be used (e.g. c("en_core_web_sm", "de_core_news_sm")). A list of available language models and their names is available from the spaCy language models page.

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.

Details

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").

See Also

spacy_download_langmodel()

Examples

## 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)

Install spaCy to a virtual environment

Description

Deprecated. spacy_install now installs to a virtual environment by default.

Usage

spacy_install_virtualenv(...)

Arguments

...

not used


Check whether spaCy is installed

Description

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.

Usage

spacy_is_installed(lang_models = NULL)

Arguments

lang_models

character; names of language models that must also be installed, e.g. "en_core_web_sm". If NULL (the default), only spaCy itself is checked.

Value

TRUE if spaCy and all lang_models are installed, FALSE otherwise.

See Also

spacy_install(), spacy_download_langmodel()

Examples

spacy_is_installed()
spacy_is_installed("en_core_web_sm")

Match patterns in texts using spaCy

Description

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.

Usage

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
)

Arguments

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 valuetype and case_insensitive apply, as in quanteda:

  • a character vector, in which each element describes one token, such as "tax*". The label of a match is the name of the element, or its text when it has no name; elements with the same name are alternatives for that label. An element is one token even when it contains a space, so "new york" matches nothing: give a sequence of tokens with quanteda::phrase().

  • a quanteda::phrase() object, or a list of character vectors, in which each element is a sequence of adjacent tokens, with one string for each token: phrase("new york*") is the same as list(c("new", "york*")). The strings are used as they are given, and are not tokenized by spaCy, so that they set the token boundaries: phrase("Acme , Inc.") describes three tokens. The label is the name of the element, or else its strings joined by a space.

  • a quanteda dictionary, which is converted with as_entity_patterns(), given valuetype and case_insensitive: the top-level keys are the labels. A value that has no wildcard (or any value, with valuetype = "fixed") is a phrase that spaCy tokenizes; a value with a wildcard, or a regular expression, is split at its spaces, with one part for each token.

  • the collocations found by quanteda.textstats::textstat_collocations(), each of which is a sequence of its words, labelled by the collocation. The words are matched as they are, as quanteda matches collocations: only case_insensitive applies, and a * matches a *. Use phrase() on the collocations to have them read according to valuetype.

The others are in spaCy's own structure, and set how they match themselves:

  • a named list, in which each name is the label of a pattern, and each element is a pattern in spaCy's structure. The names must be unique. An element is one of two kinds, and a list can hold both:

    • a token pattern, for a sequence of adjacent tokens: a list with one named list of attributes for each token, such as list(list(LOWER = "new"), list(LOWER = "york")). An element can also be a list of such token patterns, which are then alternatives for that label.

    • a dependency pattern, for tokens related in the dependency parse: a list of nodes, each a named list that describes one token, with RIGHT_ID, a name for the node, which labels the token it matches in the output; RIGHT_ATTRS, the attributes of the token as in a token pattern, such as list(DEP = "nsubjpass"), or an empty list() for any token; and, for every node but the first, LEFT_ID and REL_OP, the name of an earlier node and the operator that relates that node to this one, such as ">" when this node is a direct dependent of the earlier one. An element whose nodes have these keys is read as a dependency pattern. Each label has one dependency pattern: give alternative patterns labels of their own.

    Such a list can also hold character vectors, which are sequences as in a list of character vectors, and need no name.

  • a spacyr_entity_patterns object from as_entity_patterns(), whose labels become the labels of the matches. Patterns with the same label are alternatives for that label, and the IDs of the patterns are ignored. The object can hold phrases as well as token patterns; its phrases are tokenized by spaCy, and match exactly or in any case as the object says.

valuetype

how the strings of lexical patterns are read: "glob" (the default) for wildcards, where * stands for any number of characters and ⁠?⁠ for one; "regex" for regular expressions; or "fixed" for exact matching, as in quanteda. Each string is compared with one token, and a glob or a fixed string must match the whole of it, while a regular expression can match any part. Regular expressions are those of Python's re module, not of R or of quanteda: "^\\p{L}+$", for instance, works in quanteda and is an error here.

case_insensitive

logical; if TRUE (the default, as in quanteda), lexical patterns match in any case.

valuetype and case_insensitive are an error when they are given and pattern holds no lexical pattern: only spaCy's token or dependency patterns, or a spacyr_entity_patterns object, whose phrases have their own case_insensitive.

overlap

which matches of sequences to return where matches of the same label overlap: "longest" (the default) keeps the longest of them, and of those of the same length the one that starts first; "first" keeps the one that starts first, and of those with the same start the longest; "all" returns every match, including those inside or overlapping another, as spaCy does. Matches of different labels can overlap whatever the value. It does not apply to dependency patterns, all of whose matches are returned: in a list that holds both kinds it applies to the token patterns, and it has no effect when pattern holds only dependency patterns, so that it can be given whatever the patterns are.

n_process

the number of processes for spaCy's nlp.pipe() to use: 1 (the default) processes the documents in the current R session's Python process, a larger number starts that many Python processes, and -1 uses all CPUs. Starting the processes and loading the model in each takes time, so more than one process helps only for large numbers of documents. A custom pipeline component must be defined in an importable Python module to be used in other processes.

batch_size

the number of documents that spaCy's nlp.pipe() processes together; NULL (the default) uses the pipeline's default (nlp.batch_size). Larger batches can be faster, but use more memory.

...

not used. An argument that is not one of those of this function is an error.

offsets

logical; if TRUE, also return the position of each match in its text as it was given in x, in the columns start and end: the positions of its first and last characters, counted from 1 as in spacy_parse(), so that substring(text, start, end) gives the matches of a text. It comes after ..., so it has to be given by its full name.

Details

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).

Value

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_id

the document

match_id

the number of the match within the document, starting at 1 in each document, so that doc_id and match_id together identify a match

label

the label of the pattern that matched. It does not say which of a label's alternative patterns matched, which spaCy does not report.

node

for 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.

text

the matched text: of the whole sequence, or of the node's token

start_id

the 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

length

the 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.

Kinds of pattern

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.

Matches and quanteda

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().

Components that are left out

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 (⁠_⁠).

See Also

as_entity_patterns() and spacy_initialize() to make matches named entities, and as_index() to show matches in their context with quanteda::kwic().

Examples

## 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)

Parse a text using spaCy

Description

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).

Usage

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,
  ...
)

Arguments

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 TRUE, report named entities

dependency

logical; if TRUE, analyse and tag dependencies

nounphrase

logical; if TRUE, analyse and tag noun phrases tags

multithread

deprecated; it no longer has any effect, and gives a warning if supplied. Documents are always processed in batches with spaCy's nlp.pipe(); use n_process and batch_size instead.

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 additional_attributes = c("is_punct"), the output will include an additional variable named is_punct, which is a Boolean (in R, logical) variable indicating whether the token is a punctuation. A full list of available attributes is available from https://spacy.io/api/token#attributes.

n_process

the number of processes for spaCy's nlp.pipe() to use: 1 (the default) processes the documents in the current R session's Python process, a larger number starts that many Python processes, and -1 uses all CPUs. Starting the processes and loading the model in each takes time, so more than one process helps only for large numbers of documents. A custom pipeline component must be defined in an importable Python module to be used in other processes.

batch_size

the number of documents that spaCy's nlp.pipe() processes together; NULL (the default) uses the pipeline's default (nlp.batch_size). Larger batches can be faster, but use more memory.

offsets

logical; if TRUE, return the position of each token in its text as it was given in x, in two columns after token: start, the position of the token's first character, and end, that of its last. Positions are counted from 1 in characters as R counts them, whitespace included, so that substring(text, start, end) gives the tokens of a text. Some of spaCy's tokenizers, such as the one for Korean, make a document whose whitespace differs from that of the text; the positions are still those in the text. If a tokenizer changes anything else, so that a token is not found in the text or the text has more than whitespace outside the tokens, this is an error.

...

not used directly

Details

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.

Value

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().

Examples

## 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)

Tokenize text with spaCy

Description

Efficient tokenization (without POS tagging, dependency parsing, lemmatization, or named entity recognition) of texts using spaCy.

Usage

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,
  ...
)

Arguments

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:

"word"

word segmenter

"sentence"

sentence segmenter

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_punct) have to be set to FALSE. When what = "sentence", this option will remove trailing spaces if TRUE.

remove_symbols

remove symbols. The symbols are either SYM in pos field, or currency symbols. Since this needs the part of speech, it runs the components of the pipeline that set it, which makes tokenization much slower; the other ⁠remove_*⁠ options do not.

padding

if TRUE, leave an empty string where the removed tokens previously existed. This is useful if a positional match is needed between the pre- and post-selected tokens, for instance if a window of adjacency needs to be computed.

multithread

deprecated; it no longer has any effect, and gives a warning if supplied. Documents are always processed in batches with spaCy's nlp.pipe(); use n_process and batch_size instead.

output

type of returning object. Either list or data.frame.

n_process

the number of processes for spaCy's nlp.pipe() to use, as in spacy_parse(): 1 (the default) uses the current R session's Python process, a larger number starts that many Python processes, and -1 uses all CPUs. It is used only when components of the pipeline run, which is for what = "sentence" and for remove_symbols = TRUE. Splitting texts into words runs no components, so more processes would only add the time to start them: the words are always tokenized in one process, whatever n_process is.

batch_size

the number of documents that spaCy's nlp.pipe() processes together; NULL (the default) uses the pipeline's default (nlp.batch_size). Larger batches can be faster, but use more memory.

...

not used directly

Details

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.

Value

either list or data.frame of tokens

Examples

## 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)

Uninstall the spaCy environment

Description

Removes the virtual environment created by spacy_install()

Usage

spacy_uninstall(confirm = interactive())

Arguments

confirm

logical; confirm before uninstalling spaCy?


Shorthand function to upgrade spaCy

Description

Upgrade spaCy (to a specific version).

Usage

spacy_upgrade(
  version = "latest",
  lang_models = NULL,
  ask = interactive(),
  force = TRUE,
  ...
)

Arguments

version

character; spaCy version to install (see details).

lang_models

character; language models to be installed. Defaults en_core_web_sm (English model). A vector of multiple model names can be used (e.g. c("en_core_web_sm", "de_core_news_sm")). A list of available language models and their names is available from the spaCy language models page.

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 spacy_install()

Details

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").

See Also

spacy_download_langmodel()

Examples

## 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)