Skip to content

API reference

Formatter

spacy_conll.formatter

The conll_formatter pipeline component.

ConllFormatter dataclass

ConllFormatter(
    conversion_maps: dict[str, dict[str, str]]
    | None = None,
    ext_names: dict[str, str] = dict(),
    field_names: dict[str, str] = dict(),
    include_headers: bool = False,
    disable_pandas: bool = False,
    columns: list[str] | None = None,
)

spaCy component that adds CoNLL-U representations to docs, sentences and tokens.

The extension conll holds a dict of field names to values on a Token, a list of those dicts on a sentence Span, and a list of sentence lists on a Doc. The extension conll_str holds the tab-separated CoNLL-U text, and conll_pd (when pandas is installed and disable_pandas is false) holds a pandas Series or DataFrame. The pandas object is built from conll on access and is not stored in the doc, so docs can be saved with DocBin and sent between processes. Multi-word tokens and empty nodes are not supported.

Parameters:

Name Type Description Default
conversion_maps dict[str, dict[str, str]] | None

Maps a field name to a map of output values, for example {"LEMMA": {"-PRON-": "PRON"}} replaces the lemma -PRON- with PRON.

None
ext_names dict[str, str]

New names for the extensions conll, conll_str and conll_pd, for example {"conll": "conll_dict"}.

dict()
field_names dict[str, str]

New names for the CoNLL-U fields ID, FORM, LEMMA, UPOS, XPOS, FEATS, HEAD, DEPREL, DEPS and MISC, for example {"UPOS": "upostag"}.

dict()
include_headers bool

Whether conll_str of a sentence starts with the # sent_id and # text comment lines.

False
disable_pandas bool

Whether to skip the conll_pd extension even if pandas is installed.

False
columns list[str] | None

The CoNLL-U Plus columns to write, in this order. None uses Doc._.conll_columns if the doc has it (a doc that was read from CoNLL-U Plus text), and plain CoNLL-U otherwise. With columns, conll_str of the doc starts with a # global.columns line. The names are the CoNLL-U names (also when field_names renames them) or custom names such as PARSEME:MWE. A custom column takes its value from the dict in Token._.conll_custom_columns, and is _ when the dict does not have it.

None

Examples:

import spacy
nlp = spacy.blank("en")
_ = nlp.add_pipe("sentencizer")
_ = nlp.add_pipe(
    "conll_formatter", config={"include_headers": True}
)
doc = nlp("Hello world.")
doc[1]._.conll
# {'ID': 2, 'FORM': 'world', 'LEMMA': '_', 'UPOS': '_', 'XPOS': '_',
#  'FEATS': '_', 'HEAD': '_', 'DEPREL': '_', 'DEPS': '_',
#  'MISC': 'SpaceAfter=No'}
print(doc._.conll_str.replace("\t", " "))
# # sent_id = 1
# # text = Hello world.
# 1 Hello _ _ _ _ _ _ _ _
# 2 world _ _ _ _ _ _ _ SpaceAfter=No
# 3 . _ _ _ _ _ _ _ SpaceAfter=No

__post_init__

__post_init__()

Merge the custom names into the defaults and register extensions.

__call__

__call__(doc: Doc) -> Doc

Set the CoNLL extensions on doc, its sentences and its tokens.

Parameters:

Name Type Description Default
doc Doc

The input doc.

required

Returns:

Type Description
Doc

The same doc with the extensions set.

create_conll_formatter

create_conll_formatter(
    nlp: Language,
    name: str,
    conversion_maps: dict[str, dict[str, str]]
    | None = None,
    ext_names: dict[str, str] | None = None,
    field_names: dict[str, str] | None = None,
    include_headers: bool = False,
    disable_pandas: bool = False,
    columns: list[str] | None = None,
) -> ConllFormatter

Create the conll_formatter pipeline component.

Parameters:

Name Type Description Default
nlp Language

The pipeline, as required by spaCy.

required
name str

The component name, as required by spaCy.

required
conversion_maps dict[str, dict[str, str]] | None

See ConllFormatter.

None
ext_names dict[str, str] | None

See ConllFormatter.

None
field_names dict[str, str] | None

See ConllFormatter.

None
include_headers bool

See ConllFormatter.

False
disable_pandas bool

See ConllFormatter.

False
columns list[str] | None

See ConllFormatter.

None

Returns:

Type Description
ConllFormatter

The component.

get_whitespace_misc

get_whitespace_misc(token: Token) -> str

Describe the whitespace around a token in the MISC notation of UD.

The whitespace after a token is its own trailing space plus the text of the whitespace tokens that follow it, also when these tokens belong to the next sentence. A single space gives _, no whitespace gives SpaceAfter=No and anything else gives SpacesAfter with the escapes \s, \t, \n and \r. Whitespace at the start of the doc gives SpacesBefore on the first token that is not whitespace. See https://universaldependencies.org/misc.html.

Parameters:

Name Type Description Default
token Token

A token that is not whitespace.

required

Returns:

Type Description
str

The MISC value.

Examples:

import spacy
doc = spacy.blank("en")("\nHello  world.\t")
[t.text for t in doc]
# ['\n', 'Hello', ' ', 'world', '.', '\t']
[get_whitespace_misc(t) for t in doc if not t.is_space]
# ['SpacesAfter=\\s\\s|SpacesBefore=\\n', 'SpaceAfter=No', 'SpacesAfter=\\t']

merge_misc

merge_misc(misc: str, whitespace_misc: str) -> str

Replace the whitespace entries in a MISC value and keep the others.

The entries SpaceAfter, SpacesAfter and SpacesBefore of misc are replaced by those of whitespace_misc in the same position, or removed when whitespace_misc has no such entry. New whitespace entries go at the end. spaCy stores the whitespace after a token as a single space or nothing, so an existing SpacesAfter (for example read from a CoNLL-U file) stays when the token is followed by a single space. An existing SpacesBefore stays when whitespace_misc has none.

Parameters:

Name Type Description Default
misc str

The current MISC value, _ if empty.

required
whitespace_misc str

The output of get_whitespace_misc.

required

Returns:

Type Description
str

The merged MISC value, _ if empty.

Examples:

merge_misc("Translit=a|SpaceAfter=No", "_")
# 'Translit=a'
merge_misc("Translit=a", "SpaceAfter=No")
# 'Translit=a|SpaceAfter=No'
merge_misc("SpacesAfter=\\n|Translit=a", "_")
# 'SpacesAfter=\\n|Translit=a'
merge_misc("SpacesAfter=\\n|Translit=a", "SpaceAfter=No")
# 'Translit=a|SpaceAfter=No'
merge_misc("SpacesBefore=\\n|Translit=a", "_")
# 'SpacesBefore=\\n|Translit=a'

Parser

spacy_conll.parser

Convert text to CoNLL-U and CoNLL-U to spaCy docs.

NER_TAG_PATTERN module-attribute

NER_TAG_PATTERN = '^((?:name|NE)=)?([BILU])-([A-Z_]+)|O$'

ConllParser dataclass

ConllParser(nlp: Language)

Wrapper around a pipeline with conll_formatter that parses text and files.

The backend ("spacy" or "udpipe") is detected from the tokenizer of nlp and stored in parser.

Parameters:

Name Type Description Default
nlp Language

A pipeline that contains the conll_formatter component, for example the output of init_parser.

required

Raises:

Type Description
ValueError

If nlp has no conll_formatter component.

__post_init__

__post_init__()

Check the pipeline and detect the backend.

__repr__

__repr__() -> str

parse_file_as_conll

parse_file_as_conll(
    input_file: str | PathLike[str],
    *,
    input_encoding: str = "utf-8",
    n_process: int = 1,
    renumber_sent_ids: bool = True,
    ignore_pipe_errors: bool = False,
    split_on_newline: bool = True,
    sent_ids: Iterable[str | int] | None = None,
) -> str

Parse a text file and return its CoNLL-U representation.

Parameters:

Name Type Description Default
input_file str | PathLike[str]

Path to the text file.

required
input_encoding str

Encoding of input_file.

'utf-8'
n_process int

See parse_text_as_conll.

1
renumber_sent_ids bool

See parse_text_as_conll.

True
ignore_pipe_errors bool

See parse_text_as_conll.

False
split_on_newline bool

See parse_text_as_conll.

True
sent_ids Iterable[str | int] | None

See parse_text_as_conll.

None

Returns:

Type Description
str

The CoNLL-U string of all sentences in the file.

parse_text_as_conll

parse_text_as_conll(
    text: str,
    *,
    n_process: int = 1,
    renumber_sent_ids: bool = True,
    ignore_pipe_errors: bool = False,
    split_on_newline: bool = True,
    sent_ids: Iterable[str | int] | None = None,
) -> str

Parse a text and return its CoNLL-U representation.

Each line is a separate doc in nlp.pipe, so # sent_id would restart at 1 for every line. With renumber_sent_ids, the sentences are numbered 1, 2, 3 and so on over the whole text instead. This only matters when the formatter has include_headers=True. With sent_ids, the sentences get your own IDs instead, in order of the output.

Parameters:

Name Type Description Default
text str

The text to parse.

required
n_process int

Number of processes for nlp.pipe. -1 uses all cores. Values other than 1 may not work with UDPipe.

1
renumber_sent_ids bool

Whether to number # sent_id consecutively over the whole text.

True
ignore_pipe_errors bool

Whether to skip the checks that raise an OSError when n_process is likely to fail on this system.

False
split_on_newline bool

Whether to split the text on newlines and pass every line to nlp.pipe separately. This is faster for long texts.

True
sent_ids Iterable[str | int] | None

One ID per output sentence for the # sent_id lines. An ID cannot be empty or contain whitespace. It replaces the generated numbers and renumber_sent_ids has no effect. Requires include_headers=True in the formatter. With disable_sbd=True in init_parser, every input line is one sentence, so you can give one ID per line.

None

Returns:

Type Description
str

The CoNLL-U string, with one empty line between sentences. It

str

starts with a # global.columns line when the formatter has

str

columns.

Raises:

Type Description
OSError

If n_process is not 1, ignore_pipe_errors is false, and the backend is UDPipe on Windows.

ValueError

If sent_ids is given without include_headers, if an ID is empty or contains whitespace, or if the number of IDs differs from the number of sentences.

Examples:

from spacy_conll import init_parser
nlp = init_parser(
    "en_core_web_sm",
    "spacy",
    disable_sbd=True,
    formatter_config={"include_headers": True},
)
conll = ConllParser(nlp).parse_text_as_conll(
    "I like cookies.\nMe too.",
    sent_ids=["doc1-008", "doc1-009"],
)
[line for line in conll.splitlines() if line.startswith("#")]
# ['# sent_id = doc1-008', '# text = I like cookies.', '# sent_id = doc1-009', '# text = Me too.']

parse_conll_file_as_spacy

parse_conll_file_as_spacy(
    input_file: str | PathLike[str],
    *,
    input_encoding: str = "utf-8",
    ner_tag_pattern: str = NER_TAG_PATTERN,
    ner_map: dict[str, str] | None = None,
    strict: bool = True,
) -> Doc

Read a CoNLL-U file into a spaCy doc.

See parse_conll_text_as_spacy.

Parameters:

Name Type Description Default
input_file str | PathLike[str]

Path to the CoNLL-U file.

required
input_encoding str

Encoding of input_file.

'utf-8'
ner_tag_pattern str

Regex for the entity tag in the MISC field.

NER_TAG_PATTERN
ner_map dict[str, str] | None

Maps old entity labels to new ones. A label that maps to "" becomes O.

None
strict bool

See parse_conll_text_as_spacy.

True

Returns:

Type Description
Doc

A doc with all sentences of the file and the CoNLL extensions.

parse_conll_text_as_spacy

parse_conll_text_as_spacy(
    text: str,
    *,
    ner_tag_pattern: str = NER_TAG_PATTERN,
    ner_map: dict[str, str] | None = None,
    strict: bool = True,
) -> Doc

Read CoNLL-U text into a spaCy doc.

Sentences are separated by an empty line, and every sentence block becomes one spaCy sentence. Fields that spaCy does not store are kept in extensions: DEPS in Token._.conll_deps_graphs_field, MISC in Token._.conll_misc_field and the comment lines in Span._.conll_metadata of the sentence. A _ in LEMMA, UPOS, XPOS or FEATS leaves that attribute empty in spaCy, and the formatter writes _ again. Multi-word tokens and empty nodes are not supported. Adapted from spaCy's conllu2json converter.

With strict=False, HEAD and DEPREL may be _ (both on the same line), for example in a file that is tagged but not parsed. Such a token has no head in spaCy (token.has_head() is false and token.dep_ is ""), and the formatter writes _ for both fields. The HEAD values of a sentence then do not have to form one tree.

CoNLL-U Plus is supported: when the first line is a # global.columns comment, the lines have these columns in this order. A standard column that is missing gets the value _, and an ID column that is missing gets the token position. Custom columns such as PARSEME:MWE are kept in the dict Token._.conll_custom_columns. The # global.columns line is not part of Span._.conll_metadata. The columns are stored in Doc._.conll_columns, which the formatter uses to write the doc again unless it has its own columns.

Parameters:

Name Type Description Default
text str

CoNLL-U text.

required
ner_tag_pattern str

Regex for the entity tag in the MISC field.

NER_TAG_PATTERN
ner_map dict[str, str] | None

Maps old entity labels to new ones. A label that maps to "" becomes O.

None
strict bool

Whether every token needs a HEAD and a DEPREL, and the HEAD values of every sentence must form one tree.

True

Returns:

Type Description
Doc

A doc with all sentences of the text and the CoNLL extensions.

Raises:

Type Description
ValueError

If a line does not have 10 fields (or as many as the # global.columns line lists), a field is empty, a field other than FORM, LEMMA, MISC or a custom column contains a space, ID or HEAD is not a valid number, only one of HEAD and DEPREL is _, or # global.columns has an invalid column name. With strict=True also if HEAD or DEPREL is _, or if the HEAD values of a sentence do not form one tree. The message starts with the line number.

NotImplementedError

If the text has multi-word tokens or empty nodes.

Examples:

import spacy
nlp = spacy.blank("en")
_ = nlp.add_pipe(
    "conll_formatter", config={"include_headers": True}
)
conll = "\n".join(
    [
        "# sent_id = a1",
        "1\tHi\thi\tINTJ\tUH\t_\t0\troot\t0:root\t_",
        "2\tthere\tthere\tADV\tRB\t_\t1\tadvmod\t1:advmod\tSpaceAfter=No",
    ]
)
doc = ConllParser(nlp).parse_conll_text_as_spacy(conll)
[(t.text, t.dep_, t.head.text) for t in doc]
# [('Hi', 'ROOT', 'Hi'), ('there', 'advmod', 'Hi')]
print(doc._.conll_str.replace("\t", " "))
# # sent_id = a1
# 1 Hi hi INTJ UH _ 0 root 0:root _
# 2 there there ADV RB _ 1 advmod 1:advmod SpaceAfter=No

A sentence without dependency annotation needs strict=False:

conll = "1\tHi\thi\tINTJ\tUH\t_\t_\t_\t_\t_"
doc = ConllParser(nlp).parse_conll_text_as_spacy(
    conll, strict=False
)
[(t.text, t.dep_, t.has_head()) for t in doc]
# [('Hi', '', False)]
print(doc._.conll_str.replace("\t", " "))
# # sent_id = 1
# # text = Hi
# 1 Hi hi INTJ UH _ _ _ _ _

Utilities

spacy_conll.utils

Parser initialization, pretokenization and sentence segmentation helpers.

SpacyPretokenizedTokenizer

SpacyPretokenizedTokenizer(vocab: Vocab)

spaCy tokenizer that splits text on whitespace only.

Parameters:

Name Type Description Default
vocab Vocab

The vocab of the pipeline.

required

Examples:

tokenizer = SpacyPretokenizedTokenizer(Vocab())
[t.text for t in tokenizer("He 's here .")]
# ['He', "'s", 'here', '.']
len(tokenizer(""))
# 0

Store the vocab.

__call__

__call__(inp: str) -> Doc

Split inp on whitespace into a Doc.

Parameters:

Name Type Description Default
inp str

The text to split.

required

Returns:

Type Description
Doc

A Doc with one token per whitespace-separated part. The last

Doc

token has trailing whitespace only if inp ends with

Doc

whitespace.

Raises:

Type Description
ValueError

If inp is not a string.

SpacyDisableSentenceSegmentation

spaCy component that marks every token as not starting a sentence.

This disables the sentence boundaries of the dependency parser. The senter and sentencizer components must be excluded as well.

__call__

__call__(doc: Doc) -> Doc

Set is_sent_start to False for every token.

Parameters:

Name Type Description Default
doc Doc

The input doc.

required

Returns:

Type Description
Doc

The same doc.

init_parser

init_parser(
    model_or_lang: str,
    parser: Literal["spacy", "udpipe"],
    *,
    is_tokenized: bool = False,
    disable_sbd: bool = False,
    exclude_spacy_components: list[str] | None = None,
    parser_opts: dict[str, Any] | None = None,
    formatter_config: dict[str, Any] | None = None,
) -> Language

Load a spaCy or UDPipe pipeline and add conll_formatter last.

The UDPipe backend needs spacy-udpipe and downloads its model automatically. A spaCy model must be installed.

Parameters:

Name Type Description Default
model_or_lang str

Name of a spaCy model ("en_core_web_sm") or a language code for UDPipe ("en").

required
parser Literal['spacy', 'udpipe']

The backend to use.

required
is_tokenized bool

Whether the input text is already split into tokens separated by whitespace. This also disables sentence segmentation. Only supported for spaCy.

False
disable_sbd bool

Whether to disable automatic sentence boundary detection. Only supported for spaCy.

False
exclude_spacy_components list[str] | None

spaCy components to exclude from the pipeline, which speeds up processing. Only used for spaCy.

None
parser_opts dict[str, Any] | None

Keyword arguments for spacy.load. Ignored for UDPipe.

None
formatter_config dict[str, Any] | None

Config for the conll_formatter component, for example {"include_headers": True}. See ConllFormatter.

None

Returns:

Type Description
Language

The pipeline with conll_formatter as its last component.

Raises:

Type Description
ValueError

If parser is not one of the supported backends.

Examples:

nlp = init_parser(
    "en_core_web_sm",
    "spacy",
    formatter_config={"include_headers": True},
)
nlp.pipe_names[-1]
# 'conll_formatter'

merge_dicts_strict

merge_dicts_strict(d1: dict, d2: dict) -> dict

Overwrite the values of d1 with those of d2, in place.

Every key of d2 must already exist in d1.

Parameters:

Name Type Description Default
d1 dict

The base dict. It is modified in place.

required
d2 dict

The new values.

required

Returns:

Type Description
dict

The updated d1.

Raises:

Type Description
KeyError

If d2 has a key that is not in d1.

Examples:

merge_dicts_strict({"conll": "conll"}, {"conll": "conllu"})
# {'conll': 'conllu'}
merge_dicts_strict({"conll": "conll"}, {"conlll": "conllu"})
# Traceback (most recent call last):

# KeyError: "Unknown key 'conlll'. Valid keys are ['conll']"

create_spacy_disable_sentence_segmentation

create_spacy_disable_sentence_segmentation(
    nlp: Language, name: str
) -> SpacyDisableSentenceSegmentation

Create the disable_sbd pipeline component.

Parameters:

Name Type Description Default
nlp Language

The pipeline, as required by spaCy.

required
name str

The component name, as required by spaCy.

required

Returns:

Type Description
SpacyDisableSentenceSegmentation

The component.