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 |
None
|
ext_names
|
dict[str, str]
|
New names for the extensions |
dict()
|
field_names
|
dict[str, str]
|
New names for the CoNLL-U fields |
dict()
|
include_headers
|
bool
|
Whether |
False
|
disable_pandas
|
bool
|
Whether to skip the |
False
|
columns
|
list[str] | None
|
The CoNLL-U Plus columns to write, in this order. |
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__
¶
Merge the custom names into the defaults and register extensions.
View source on GitHub: src/spacy_conll/formatter.py lines 245–261
__call__
¶
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. |
View source on GitHub: src/spacy_conll/formatter.py lines 263–295
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 |
None
|
ext_names
|
dict[str, str] | None
|
See |
None
|
field_names
|
dict[str, str] | None
|
See |
None
|
include_headers
|
bool
|
See |
False
|
disable_pandas
|
bool
|
See |
False
|
columns
|
list[str] | None
|
See |
None
|
Returns:
| Type | Description |
|---|---|
ConllFormatter
|
The component. |
View source on GitHub: src/spacy_conll/formatter.py lines 526–569
get_whitespace_misc
¶
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']
View source on GitHub: src/spacy_conll/formatter.py lines 77–123
merge_misc
¶
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, |
required |
whitespace_misc
|
str
|
The output of |
required |
Returns:
| Type | Description |
|---|---|
str
|
The merged MISC value, |
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'
View source on GitHub: src/spacy_conll/formatter.py lines 126–177
Parser¶
spacy_conll.parser
¶
Convert text to CoNLL-U and CoNLL-U to spaCy docs.
ConllParser
dataclass
¶
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 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
__post_init__
¶
Check the pipeline and detect the backend.
View source on GitHub: src/spacy_conll/parser.py lines 46–60
__repr__
¶
Return the class name and the backend.
View source on GitHub: src/spacy_conll/parser.py lines 62–64
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 |
'utf-8'
|
n_process
|
int
|
See |
1
|
renumber_sent_ids
|
bool
|
See |
True
|
ignore_pipe_errors
|
bool
|
See |
False
|
split_on_newline
|
bool
|
See |
True
|
sent_ids
|
Iterable[str | int] | None
|
See |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The CoNLL-U string of all sentences in the file. |
View source on GitHub: src/spacy_conll/parser.py lines 66–100
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 |
1
|
renumber_sent_ids
|
bool
|
Whether to number |
True
|
ignore_pipe_errors
|
bool
|
Whether to skip the checks that raise an
|
False
|
split_on_newline
|
bool
|
Whether to split the text on newlines and pass
every line to |
True
|
sent_ids
|
Iterable[str | int] | None
|
One ID per output sentence for the |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The CoNLL-U string, with one empty line between sentences. It |
str
|
starts with a |
str
|
|
Raises:
| Type | Description |
|---|---|
OSError
|
If |
ValueError
|
If |
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.']
View source on GitHub: src/spacy_conll/parser.py lines 102–234
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 |
'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
|
None
|
strict
|
bool
|
See |
True
|
Returns:
| Type | Description |
|---|---|
Doc
|
A doc with all sentences of the file and the CoNLL extensions. |
View source on GitHub: src/spacy_conll/parser.py lines 236–266
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
|
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
|
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 _ _ _ _ _
View source on GitHub: src/spacy_conll/parser.py lines 268–554
Utilities¶
spacy_conll.utils
¶
Parser initialization, pretokenization and sentence segmentation helpers.
SpacyPretokenizedTokenizer
¶
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.
View source on GitHub: src/spacy_conll/utils.py lines 146–148
__call__
¶
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
|
token has trailing whitespace only if |
Doc
|
whitespace. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
View source on GitHub: src/spacy_conll/utils.py lines 150–174
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__
¶
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. |
View source on GitHub: src/spacy_conll/utils.py lines 184–195
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 ( |
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 |
None
|
formatter_config
|
dict[str, Any] | None
|
Config for the |
None
|
Returns:
| Type | Description |
|---|---|
Language
|
The pipeline with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
nlp = init_parser(
"en_core_web_sm",
"spacy",
formatter_config={"include_headers": True},
)
nlp.pipe_names[-1]
# 'conll_formatter'
merge_dicts_strict
¶
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 |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
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']"
View source on GitHub: src/spacy_conll/utils.py lines 101–129
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. |
View source on GitHub: src/spacy_conll/utils.py lines 198–211